OLTP
medium 28 minOLTP, online transaction processing, is the work of recording business events as they happen: an order, a payment, a booking.
See it run
Short transactions on a few rows: place an order, sell the last one, move money, and survive a crash.
Operations
Place an order
Alice buys two pieces. Five tables, one transaction.
Step 1 of 7
Begin
| table | row of interest |
|---|---|
| customers | C-42 Alice |
| products | P-100 at 49.99 |
| inventory | P-100 stock 50 |
| orders | |
| order_items |
ORD-1001 begins
Alice presses Buy now. A transaction starts; until commit, nobody else sees its changes.
Step 1: Begin
BEGIN;SELECT id, name FROM customers WHERE id = 'C-42';UPDATE inventory SET stock = stock - 2 WHERE product_id = 'P-100' AND stock >= 2;INSERT INTO orders VALUES ('ORD-1001', 'C-42', 99.98);INSERT INTO order_items VALUES ('ORD-1001', 'P-100', 2, 49.99);COMMIT;- Rows touched
- 5 rows
- Lock held
- A few ms
- Five separate saves
- half an order is possible
The update comes before the inserts here, so a lack of stock ends the work early.
In the real world
The same oltp doing real jobs. Pick one and step through it.
A dashboard asks the shop database a huge question. The gauges are an example.
Step 1 of 4
Normal
- Database CPU
- 35%
All good
Shoppers get quick answers.
Step 1: Normal
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Read, decide, write without a lock
criticalTwo requests read the same stock and both sell it.
Wrongif stock(p) >= q: set_stock(p, stock(p) - q)Rightn = sql("UPDATE inventory SET stock = stock - ? " "WHERE id = ? AND stock >= ?", q, p, q)if n != 1: rollback()A remote call inside a transaction
criticalThe lock is held for as long as another company needs.
Wrongbegin(); take_stock()pay(card)commit()Rightbegin(); reserve(); commit()pay(card, key=order_id)begin(); confirm(); commit()Money as floating point
major0.1 + 0.2 is not exactly 0.3, and the cents drift.
Wrongtotal = 0.1 + 0.2 # 0.30000000000000004Righttotal = 10 + 20 # whole centsOne connection per request
majorOpening is slow and the limit is reached at the worst moment.
Wrongconn = connect()run(conn)Rightwith pool.connection() as conn: run(conn)
Interview tips
How to explain it
- Many users, short transactions, few rows.
- Correct through ACID.
- Fast through keys and short locks.
Memory trick: fast cashier
- Online: one request, answered now
- Low latency
- Thousands of users
- Point queries
Reach for it when
- Somebody books, buys or pays.
- Several rows change together.
- The answer must be right now.
Keep away
- Reports over millions of rows.
- Long transactions.
- Indexes nobody uses.