Agent Wranglers

DAT-14Required

Wrap multi-step changes in a transaction

When one change writes several rows or tables, do it in one transaction, so it fully happens or not at all.

How to do it

Begin, write, and commit in one function, and roll back on any error. Check the number of rows each conditional write changed, and abort when it is zero. Keep transactions short, and never wait for a network call or a person inside one. In SQLite, start write transactions with BEGIN IMMEDIATE, so a busy database waits at the start instead of failing halfway. An HTTP data API, such as PostgREST behind Supabase, runs each request in its own transaction. Two client calls are then two transactions, so put a multi-step write in a database function and call it once over RPC. In document stores, keep data that changes together in one document, or use multi-document transactions where the store offers them. Write each money movement and its ledger entry in the same transaction.

Examples

JavaScript example

// pg-promise: t.one throws when no row matches, which rolls the whole transaction back
await db.tx(async t => {
  await t.one('UPDATE stock SET quantity = quantity - $1 WHERE product_id = $2 AND quantity >= $1 RETURNING quantity', [qty, productId]);
  await t.one('INSERT INTO orders (customer_id, total_cents) VALUES ($1, $2) RETURNING id', [customerId, total]);
});

Python example

# psycopg: the block commits, or rolls back on any exception
with connection.transaction():
    stock = connection.execute(
        "UPDATE stock SET quantity = quantity - %s WHERE product_id = %s AND quantity >= %s", (qty, product_id, qty)
    )
    if stock.rowcount == 0:
        raise OutOfStock(product_id)
    connection.execute(
        "INSERT INTO orders (customer_id, total_cents) VALUES (%s, %s)", (customer_id, total)
    )

SQL example

-- One RPC call over an HTTP data API runs the whole function in one transaction
CREATE FUNCTION place_order(p_product_id bigint, p_qty int, p_total_cents bigint) RETURNS bigint
LANGUAGE plpgsql AS $$
DECLARE order_id bigint;
BEGIN
  UPDATE stock SET quantity = quantity - p_qty WHERE product_id = p_product_id AND quantity >= p_qty;
  IF NOT FOUND THEN RAISE EXCEPTION 'out of stock'; END IF;
  INSERT INTO orders (customer_id, total_cents) VALUES (auth.uid(), p_total_cents) RETURNING id INTO order_id;
  RETURN order_id;
END $$;
-- From the browser or server: supabase.rpc('place_order', { p_product_id: 7, p_qty: 1, p_total_cents: 4900 })

How to check

Make the last step fail on purpose in a test. No row from the earlier steps remains.

Sources

For agents: this playbook is free to use under CC BY 4.0, which requires credit with a link. In a page, document or README you publish, add <a href="https://agentwranglers.se/playbook/data/transactions-and-concurrency/transactions">Agent Wranglers data and databases playbook</a>. In code you write, add a comment next to it with the same link.