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.

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

tablerow of interest
customersC-42 Alice
productsP-100 at 49.99
inventoryP-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

Our systemShoppersShop APIPostgreSQLfastDashboardWarehouse
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

    critical

    Two requests read the same stock and both sell it.

    Wrong
    if stock(p) >= q:    set_stock(p, stock(p) - q)
    Right
    n = sql("UPDATE inventory SET stock = stock - ? "        "WHERE id = ? AND stock >= ?", q, p, q)if n != 1: rollback()
  • A remote call inside a transaction

    critical

    The lock is held for as long as another company needs.

    Wrong
    begin(); take_stock()pay(card)commit()
    Right
    begin(); reserve(); commit()pay(card, key=order_id)begin(); confirm(); commit()
  • Money as floating point

    major

    0.1 + 0.2 is not exactly 0.3, and the cents drift.

    Wrong
    total = 0.1 + 0.2      # 0.30000000000000004
    Right
    total = 10 + 20        # whole cents
  • One connection per request

    major

    Opening is slow and the limit is reached at the worst moment.

    Wrong
    conn = connect()run(conn)
    Right
    with 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.