AlgoViz

OLTP

medium 28 min

OLTP, 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

0:00 / 3:47

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

  1. 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.

  2. 8 July 1969

    IBM releases CICS, a monitor that runs many short transactions from many terminals.

  3. September 1981

    Jim Gray publishes "The Transaction Concept", which names atomicity, consistency and durability.

  4. 1983

    Theo Haerder and Andreas Reuter add isolation and coin the word ACID.

  5. July 1992

    The TPC-C benchmark is approved. It imitates a wholesale company taking orders and payments.

  6. 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.

One window, many short sales
A quick queue50 seats

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

Users send requests to an app server. The app server uses a connection pool to reach a PostgreSQL primary machine, which writes a log and the tables. The log is streamed to a standby machine.
The pool keeps the number of connections small. The standby holds a second copy for a failure.

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

A B-tree reaches one row in a million in about three steps. The row: customer 123, total 149.50, pending.

Example

One order as a transaction

Alice, customer C-42, buys 2 pieces of product P-100 at 49.99. The total is 2×49.99=99.982 \times 49.99 = 99.98.

SQL
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;
If the update changes no row, the stock is too low: ROLLBACK, and nothing of the order remains.

Commit or roll back

The answer comes after the log is safe. That is why a crash right after it loses nothing.

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. 1

    No redundancy

    The customer's email is in one row, not in every order.

  2. 2

    Fast writes

    A change of email updates one row.

  3. 3

    Integrity

    Two copies cannot disagree, because there is only one.

A small shop

One customer has many orders, one order has many items, and each item points to one product.

The six tables

TableKeysOther columns
customersidname, email, created_at
ordersid, customer_idstatus, total, created_at
order_itemsid, order_id, product_idquantity, price
productsid, category_idname, description, price
inventoryproduct_idstock, reserved, last_updated
categoriesid, parent_idname
The price is in order_items too, on purpose: it is the price at that moment, a different fact from today's price.
SQL
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';
Money is numeric, never floating point. The second index holds only open orders, so it stays small.

Indexes

Enough, not many

IndexWhyWatch out
Primary keyEvery lookup by idMade automatically
Foreign keyJoins, and deletes of the parentPostgreSQL does not create it for you
Often searched columnEmail for the loginAdd unique where it is true
Few values, such as statusOnly with a condition, like open ordersA plain index on status helps little when most rows share a value
One more just in caseNothingEvery insert and many updates must maintain it
Each index makes some reads faster and every insert slower. Remove indexes that nobody uses.

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

most updates a second=1time the lock is held120 ms=5012 ms=500\text{most updates a second} = \frac{1}{\text{time the lock is held}} \qquad \tfrac{1}{20\ \text{ms}} = 50 \qquad \tfrac{1}{2\ \text{ms}} = 500
A call to a payment provider of 800 ms inside the transaction would leave a little more than one sale a second.

Three ways to protect the stock

WayHowGood when
One conditional updateSubtract where stock is enough, check the row countThe rule fits in one statement
Pessimistic lockSELECT ... FOR UPDATE, decide, then updateSeveral steps depend on the value
Optimistic lockUpdate where the version is unchanged, else try againConflicts are rare

A deadlock, and how to avoid it

With a fixed order, the second transaction waits before it holds anything. Retry a stopped transaction from its beginning.
Python
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.id
SQLAlchemy. Whole cents instead of floating point, and both rows locked in order of their id.

Scale

How much is it really?

Teams often fear numbers that a single machine handles. Calculate first.

Two million orders a day

2,000,00086,400≈23 /s×3≈70 /s at peak×6 statements≈420 /s\frac{2{,}000{,}000}{86{,}400} \approx 23\ /\text{s} \qquad \times 3 \approx 70\ /\text{s at peak} \qquad \times 6\ \text{statements} \approx 420\ /\text{s}
Assumptions: peak is 3 times the average and each order is six statements. That is moderate work for one well indexed database.

How many connections?

busy connections=transactions a second×seconds each=300×0.01=3\text{busy connections} = \text{transactions a second} \times \text{seconds each} = 300 \times 0.01 = 3
Little's law. Thousands of users do not need thousands of connections; a small pool with a short wait is enough.

When one database is busy

StepHelps withCost
Fix slow queries and indexesEverythingAttention
Pool connectionsMemory and switchingOne more part
A bigger machineReads and writesMoney, a ceiling
Read replicasReadsSlightly old data
Move reports awayReads, locks, cacheA copy to keep fresh
Partition by customerWritesTransactions over partitions are hard
Go down this list in order.

Uses

Where it runs

FieldTransactionsThe rule that must hold
BankingBalance updates, transfers, withdrawals, loan paymentsNo money appears or disappears
ShopsCarts, orders, stock, paymentsStock never below zero
AirlinesSeats, tickets, check-in, flight statusNo seat sold twice
HealthcareRegistration, appointments, prescriptions, billingOne 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

OLTPOLAP
PurposeDay-to-day workAnalysis and reports
QueriesSimple, few rowsComplex, millions of rows
UsersCustomers and clerks, very manyAnalysts and dashboards, few
Time allowedMillisecondsSeconds or minutes
SchemaNormalizedDenormalized, often a star
StorageRows togetherColumns together
Tuned forShort writes and lookupsLarge reads
Data keptWhat the business needs nowYears of history

Both, one after the other

Orders, payments and users are written to an OLTP database, PostgreSQL. Changes flow through Kafka to a data warehouse. Dashboards, reports and machine learning models read the warehouse.
The short work stays fast, because the long questions go to a copy. The copy is refreshed at night or all the time.

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.

Sources