OLTP
medium 28 minOLTP, online transaction processing, is the work of recording business events as they happen: an order, a payment, a booking.
Video lesson · Chapter 1 of 5
Two pastries left and three hungry buyers
OLTP in 90 seconds
1:30Reel coming soon
Theory
Read or listen first. About 2 min.
What it is
OLTP stands for online transaction processing. Online means now: a person or a program waits for the answer. A transaction is a small group of reads and writes that belongs together, such as taking an order and reducing the stock.
An OLTP system handles large numbers of these short transactions at the same time. Each one inserts, updates, deletes or looks up a few rows, usually by their key.
Why it exists
Every business has a moment when something becomes true: the seat is yours, the money has moved. That moment must be quick, because someone waits, and it must be exact, because two people cannot have the same seat.
Reports are different work. They read millions of rows and may take seconds. Mixing both in one database makes the short work wait for the long work, so they are designed and often stored apart.
A short history
Mid-1960s
Sabre, built by IBM and American Airlines, handles 7,500 reservations an hour and cuts the time for one from about 90 minutes to seconds.
8 July 1969
IBM releases CICS, a monitor that runs many short transactions from many terminals.
September 1981
Jim Gray publishes "The Transaction Concept", which names atomicity, consistency and durability.
1983
Theo Haerder and Andreas Reuter add isolation and coin the word ACID.
July 1992
The TPC-C benchmark is approved. It imitates a wholesale company taking orders and payments.
1993
Edgar F. Codd coins the term OLAP for analytical work, which gives OLTP its counterpart.
Words to know
- Transaction
- Several reads and writes that succeed together or not at all.
- Commit and rollback
- Make all changes permanent, or undo all of them.
- Normalized schema
- Each fact is stored once, in one table.
- Primary and foreign key
- The identifier of a row, and a column that points to another row.
- Row lock
- Lets one transaction change a row while others wait.
- Write-ahead log
- A log of changes written before the data itself, used to recover after a crash.
- Point query
- A lookup of one or a few rows by a key.
- Connection pool
- A small set of database connections shared by many requests.
Understand it
Start here
The ticket window at the funfair
Imagine a busy ticket window at a funfair. People come one after another, each wants something small, and nobody wants to wait. The clerk takes the coin, hands out the ticket and changes the count. Then the next one.
A fast cashier in a sweet shop works the same way: take the money, give the sweets, update the count, done in seconds.
The idea
What makes work OLTP
Low latency
Somebody pressed Buy and waits. A few milliseconds in the database is a common aim.
High concurrency
Very many transactions run at the same time and should rarely block each other.
ACID
Atomicity, consistency, isolation and durability keep the data right even in failures.
Frequent writes
Rows are inserted, updated and deleted all the time, mixed with many lookups.
The path of a transaction
Typical OLTP queries
- One user by id
- Insert one order
- Take 100 from one account
- The last 10 orders of one customer
Not OLTP: analysis
- Revenue of all orders by region
- Every order between two dates
- Average spend over all customers and orders
- Anything that reads most of a table
A point query touches a few pages
Example
One order as a transaction
Alice, customer C-42, buys 2 pieces of product P-100 at 49.99. The total is .
BEGIN;SELECT id, name FROM customers WHERE id = 'C-42';-- Take the stock only if there is enough. One statement, no gap.UPDATE inventory SET stock = stock - 2 WHERE product_id = 'P-100' AND stock >= 2; -- must change 1 rowINSERT INTO orders (id, customer_id, status, total)VALUES ('ORD-1001', 'C-42', 'confirmed', 99.98);INSERT INTO order_items (order_id, product_id, quantity, price)VALUES ('ORD-1001', 'P-100', 2, 49.99);COMMIT;Commit or roll back
What each letter guarantees is in ACID, and what transactions may see of each other is in isolation levels.
Schema
Why normalize
OLTP schemas are usually in third normal form: every column that is not a key depends on the key, the whole key, and nothing else. Each fact then has one home.
- 1
No redundancy
The customer's email is in one row, not in every order.
- 2
Fast writes
A change of email updates one row.
- 3
Integrity
Two copies cannot disagree, because there is only one.
A small shop
The six tables
| Table | Keys | Other columns |
|---|---|---|
| customers | id | name, email, created_at |
| orders | id, customer_id | status, total, created_at |
| order_items | id, order_id, product_id | quantity, price |
| products | id, category_id | name, description, price |
| inventory | product_id | stock, reserved, last_updated |
| categories | id, parent_id | name |
CREATE TABLE customers ( id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, name varchar(100) NOT NULL, email varchar(255) UNIQUE NOT NULL, created_at timestamptz NOT NULL DEFAULT now());CREATE TABLE orders ( id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, customer_id bigint NOT NULL REFERENCES customers(id), status varchar(20) NOT NULL DEFAULT 'pending', total numeric(10,2) NOT NULL, created_at timestamptz NOT NULL DEFAULT now());CREATE INDEX orders_customer ON orders (customer_id, created_at DESC);CREATE INDEX orders_open ON orders (created_at) WHERE status = 'pending';Indexes
Enough, not many
| Index | Why | Watch out |
|---|---|---|
| Primary key | Every lookup by id | Made automatically |
| Foreign key | Joins, and deletes of the parent | PostgreSQL does not create it for you |
| Often searched column | Email for the login | Add unique where it is true |
| Few values, such as status | Only with a condition, like open orders | A plain index on status helps little when most rows share a value |
| One more just in case | Nothing | Every insert and many updates must maintain it |
Concurrency
When two want the same row
Readers and writers rarely block each other in databases that keep several versions of a row. Two writers of one row always do: the second waits for the first. So the time you hold a lock decides how much a popular row can do.
The limit of one hot row
Three ways to protect the stock
| Way | How | Good when |
|---|---|---|
| One conditional update | Subtract where stock is enough, check the row count | The rule fits in one statement |
| Pessimistic lock | SELECT ... FOR UPDATE, decide, then update | Several steps depend on the value |
| Optimistic lock | Update where the version is unchanged, else try again | Conflicts are rare |
A deadlock, and how to avoid it
from sqlalchemy import selectfrom sqlalchemy.orm import Sessiondef transfer_funds(session: Session, from_id: int, to_id: int, cents: int) -> int: """Move money between accounts. All or nothing.""" if cents <= 0 or from_id == to_id: raise ValueError("bad transfer") with session.begin(): # commit, or roll back on any error rows = session.execute( select(Account) .where(Account.id.in_([from_id, to_id])) .order_by(Account.id) # fixed lock order: no deadlock .with_for_update() ).scalars().all() accounts = {a.id: a for a in rows} if len(accounts) != 2: raise ValueError("unknown account") if accounts[from_id].balance < cents: raise ValueError("insufficient funds") accounts[from_id].balance -= cents accounts[to_id].balance += cents entry = Transaction(from_account_id=from_id, to_account_id=to_id, amount=cents, status="completed") session.add(entry) session.flush() return entry.idScale
How much is it really?
Teams often fear numbers that a single machine handles. Calculate first.
Two million orders a day
How many connections?
When one database is busy
| Step | Helps with | Cost |
|---|---|---|
| Fix slow queries and indexes | Everything | Attention |
| Pool connections | Memory and switching | One more part |
| A bigger machine | Reads and writes | Money, a ceiling |
| Read replicas | Reads | Slightly old data |
| Move reports away | Reads, locks, cache | A copy to keep fresh |
| Partition by customer | Writes | Transactions over partitions are hard |
Uses
Where it runs
| Field | Transactions | The rule that must hold |
|---|---|---|
| Banking | Balance updates, transfers, withdrawals, loan payments | No money appears or disappears |
| Shops | Carts, orders, stock, payments | Stock never below zero |
| Airlines | Seats, tickets, check-in, flight status | No seat sold twice |
| Healthcare | Registration, appointments, prescriptions, billing | One patient, one correct record |
A card payment looks like one transaction, but it crosses companies: the shop, its bank, the card network and your bank. Within your own database you can check the account, check the balance, debit it and write the log together. Between companies there is no shared COMMIT. They exchange messages such as authorise and capture, with unique ids so that a repeat does no harm.
Compare
OLTP and OLAP
| OLTP | OLAP | |
|---|---|---|
| Purpose | Day-to-day work | Analysis and reports |
| Queries | Simple, few rows | Complex, millions of rows |
| Users | Customers and clerks, very many | Analysts and dashboards, few |
| Time allowed | Milliseconds | Seconds or minutes |
| Schema | Normalized | Denormalized, often a star |
| Storage | Rows together | Columns together |
| Tuned for | Short writes and lookups | Large reads |
| Data kept | What the business needs now | Years of history |
Both, one after the other
The other side of this picture, with star schemas and column storage, is in OLAP.
Which one is it?
Practice
Do and do not
Do
- Use a connection pool
- Keep transactions short
- Use prepared statements
- Index foreign keys
- Lock rows you decide on, in a fixed order
- Retry serialization failures and deadlocks
Do not
- Hold locks during external calls
- Run analytics on the OLTP database
- Add indexes just in case
- Use SELECT * in production
- Ignore connection limits
- Leave transactions open while a person thinks
PostgreSQL, MySQL, Oracle and SQL Server are widely used for this. They are SQL databases; some NoSQL databases also offer transactions, with their own limits.
Summary
The whole topic in one minute.
OLTP is the daily work of a business: many users, short transactions, few rows, quick answers. Correctness comes from ACID transactions, and speed comes from indexes, short locks and a normalized schema in which every fact has one place.
Keep transactions short, take locks in a fixed order, never wait for another system while holding one, and let analytics run on a copy. When one machine is not enough, read replicas come first and partitioning later.
- Many users, short transactions, few rows, quick answers.
- ACID makes it right; indexes and short locks make it fast.
- Normalize: every fact has one place.
- A hot row can do one divided by the lock time.
- Analytics belong on a copy.