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.

An order as a transaction

Read it, run it, change a line and run it again.

Loading editor…

SQLite in memory. The stock is taken with one conditional update, prices come from the database, and any error rolls everything back.

The same in JavaScript
// Node.js with the pg driver for PostgreSQLasync function placeOrder(pool, customerId, items) {  const client = await pool.connect();  try {    await client.query("BEGIN");    // 1. The customer must exist    const { rows: [customer] } = await client.query(      "SELECT id FROM customers WHERE id = $1", [customerId]);    if (!customer) throw new Error("Customer not found");    // 2. Create the order    const { rows: [order] } = await client.query(      "INSERT INTO orders (customer_id, status, total) VALUES ($1, 'pending', 0) RETURNING id",      [customerId]);    // 3. Each item, in a fixed order of product id    for (const item of [...items].sort((a, b) => a.productId - b.productId)) {      const { rows: [inv] } = await client.query(        "SELECT i.stock, p.price FROM inventory i JOIN products p ON p.id = i.product_id " +        "WHERE i.product_id = $1 FOR UPDATE OF i", [item.productId]);      if (!inv || inv.stock < item.quantity) {        throw new Error("Insufficient stock for product " + item.productId);      }      // The price comes from the database, never from the client      await client.query(        "INSERT INTO order_items (order_id, product_id, quantity, price) VALUES ($1, $2, $3, $4)",        [order.id, item.productId, item.quantity, inv.price]);      await client.query(        "UPDATE inventory SET stock = stock - $1 WHERE product_id = $2",        [item.quantity, item.productId]);    }    // 4. The total is summed by the database: exact decimals    const { rows: [done] } = await client.query(      "UPDATE orders SET status = 'confirmed', total = " +      "(SELECT sum(quantity * price) FROM order_items WHERE order_id = $1) " +      "WHERE id = $1 RETURNING id, total", [order.id]);    await client.query("COMMIT");    return { orderId: done.id, total: done.total };  } catch (error) {    await client.query("ROLLBACK");    throw error;  } finally {    client.release();   // back to the pool  }}
The same in SQL
-- OLTP: one row by its keySELECT id, customer_id, status, totalFROM ordersWHERE id = 12345;-- OLTP: the last orders of one customer, from an indexSELECT id, status, totalFROM ordersWHERE customer_id = 42ORDER BY created_at DESCLIMIT 10;-- OLAP: reads the whole table. Run it on the warehouse.SELECT c.region, sum(o.total) AS revenueFROM orders o JOIN customers c ON c.id = o.customer_idGROUP BY c.region;