Lawfare Academy

Data Management and SQL for Business · Chapter 5 of 6

Transactions, invariant checks and controlled failure

Return to the linked course unit →

DEVELOPED COURSE TEXT

Transactions, invariant checks and controlled failure

Atomicity groups the intended business change

An order reservation can require stock change, a parent order and its item rows to succeed together. A transaction defines a commit/rollback boundary for those writes. A failed individual statement does not justify assuming that every earlier statement was automatically undone; application failure handling must restore the intended boundary. Constraints remain valuable inside the transaction, but the application must also decide what constitutes a successful business operation.

Use the write condition rather than a stale read

Reading stock, deciding in application code and later writing an unconditional new value can create a race. The educational function below uses a guarded update whose predicate requires sufficient stock and checks that exactly one row changed. It then inserts the related records within the same transaction. It is a SQLite teaching example for a fixed product and price, not a production ordering service. Locking, retries, authorization, idempotency and payment integration need additional design.

Executable reservation example

Use a connection initialized with the fixture and no open transaction. The positive-integer validation avoids an invalid negative reservation. The deliberate exception path rolls back both earlier and later writes.

def reserve_order(conn, order_id, quantity):
    # conn has the fixture schema and no open transaction.
    if type(quantity) is not int or quantity <= 0:
        raise ValueError('Quantity must be a positive integer')
    conn.execute('BEGIN')
    try:
        changed = conn.execute(
            'UPDATE inventory SET on_hand=on_hand-? '
            'WHERE sku=? AND on_hand>=?',
            (quantity, 'A', quantity)
        ).rowcount
        if changed != 1:
            raise ValueError('Insufficient stock')
        conn.execute(
            'INSERT INTO orders VALUES (?,?,?,?)',
            (order_id, 4, 'unpaid', '2026-01-06')
        )
        conn.execute(
            'INSERT INTO order_items VALUES (?,?,?,?,?)',
            (100 + order_id, order_id, 'A', quantity, 1000)
        )
        conn.commit()
    except Exception:
        conn.rollback()
        raise

Auditing and permissions are separate controls

A transaction does not prove the user was authorized, the product was selected correctly or the operation was intended only once. Production systems need appropriate privileges, event identity, logs, retention and tested recovery. A retry can duplicate a business action unless the idempotency contract is designed and enforced. The presence of a transaction is therefore necessary for some invariants but not a complete system of business control.

Worked records

Record 1

Inventory A begins at 10. reserve_order(conn,6,2) succeeds. A later call reserves 99 for order 7 and fails. A third call tries to use the existing order ID 6 after decrementing one unit.

Develop the reasoning

The success leaves stock 8 and adds exactly one order and one item. The insufficient-stock call changes no row, raises an exception and leaves no order 7. The duplicate-order call reaches the uniqueness error after a guarded decrement, but the exception handler rolls back that transaction, restoring stock to 8. This last case demonstrates why handling the whole transaction matters: a later failure must not leave an earlier stock change committed. The reproducibility check executes these paths and asserts the resulting counts. It does not establish behavior of every database engine or production concurrency pattern.

Progressive practice — optional

1. Foundation

Does a successful guarded update alone mean the entire order was recorded?

Compare the worked reasoning

No. The subsequent parent/item writes and commit still need to succeed.

Change the record

The parent insert fails.

Compare the changed-record reasoning

The transaction must roll back the earlier decrement under the operation’s atomicity contract.

2. Application

What must the application check after the guarded update?

Compare the worked reasoning

That the intended row count is exactly one before continuing.

Change the record

No matching SKU exists.

Compare the changed-record reasoning

Zero changed rows is not success; handle it as a failed reservation rather than create a misleading order.

3. Transfer

A network response is lost after commit. Is blindly repeating the entire business action always safe?

Compare the worked reasoning

No. The caller may not know whether the first action committed.

Change the record

The system has a stable idempotency key and enforced duplicate-action handling.

Compare the changed-record reasoning

That can support a safe retry contract, but it must be designed and tested; atomicity alone did not supply it.

Sources and scope