Transactions and Atomic Writes

Transactions and Atomic Writes in PHP: --- When a house changes hands, the buyer's money and the seller's deed do not simply pass across a table at the same…


The Analogy: The Escrow Agent Closing a House Sale

When a house changes hands, the buyer's money and the seller's deed do not simply pass across a table at the same instant. An escrow agent holds both sides in a locked account and only completes the exchange when every condition is met: funds cleared, title searched, documents signed. If any one step fails -- a lien surfaces, a cheque bounces -- the agent unwinds everything, returning the money to the buyer and the deed to the seller, as if the deal never began. A database transaction is that escrow agent: a set of changes that either all take effect together or none do.

The crucial property is that no outside observer ever sees a half-finished deal. Nobody can peek into escrow and find the buyer's money gone but the deed not yet transferred. The transaction is invisible from the outside until it commits, at which point every change becomes visible at once. This is why a bank transfer wrapped in a transaction can never leave money debited from one account but not credited to the other, even if the power fails between the two updates.

To begin, the agent opens the escrow file; that is beginTransaction. When every step has succeeded, the agent finalises the exchange and the changes become permanent; that is commit. If anything goes wrong at any point, the agent tears up the file and restores both parties to their starting positions; that is rollBack. The whole discipline is: open, attempt every step, and then either finalise or unwind -- never leave the file half-open.

The failure mode is the agent who debits the buyer, then walks away without either finalising or unwinding when the title search fails. The money is gone from the buyer, the deed still sits with the seller, and the escrow file is left dangling. In database terms this is a transaction begun but never committed or rolled back -- perhaps because an exception skipped past both -- holding locks, blocking other work, and leaving the data in a state no one intended. Every transaction must reach exactly one of its two endings.


Syntax or Core Structure

The pattern is always the same: beginTransaction, then the writes inside a try, then commit on success. A catch calls rollBack and re-throws, so a failure undoes every change in the block. Here a money transfer debits one account and credits another as one atomic unit.

<?php
declare(strict_types=1);
$pdo = new PDO('sqlite::memory:', null, null, [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
$pdo->exec('CREATE TABLE accounts (name TEXT PRIMARY KEY, cents INTEGER NOT NULL)');
$pdo->exec("INSERT INTO accounts VALUES ('alice', 10000), ('bob', 5000)");

$move = function (PDO $pdo, string $from, string $to, int $cents): void {
    $debit  = $pdo->prepare('UPDATE accounts SET cents = cents - ? WHERE name = ?');
    $credit = $pdo->prepare('UPDATE accounts SET cents = cents + ? WHERE name = ?');
    $pdo->beginTransaction();
    try {
        $debit->execute([$cents, $from]);
        $credit->execute([$cents, $to]);
        $pdo->commit();
    } catch (Throwable $e) {
        $pdo->rollBack();
        throw $e;
    }
};

$move($pdo, 'alice', 'bob', 3000);
foreach ($pdo->query('SELECT name, cents FROM accounts ORDER BY name') as $r) {
    echo $r['name'], ' = ', $r['cents'], "\n";
}

Output:

alice = 7000
bob = 8000

The transfer of 3000 cents debits alice to 7000 and credits bob to 8000, and because both updates sit inside one transaction they commit together. If the credit had thrown -- a constraint violation, a dropped connection -- the catch would roll the debit back too, so alice would never lose money that bob failed to receive. The re-throw lets the caller know the transfer did not happen.


Technical Depth: ACID, Rollback, and Batch Speed

The guarantees a transaction makes

Transactions provide four guarantees, remembered by the acronym ACID. Understanding them clarifies what you are and are not protected against.

PropertyMeaning
AtomicityAll changes apply, or none do
ConsistencyThe database moves from one valid state to another, honouring constraints
IsolationConcurrent transactions do not see each other's partial work
DurabilityOnce committed, changes survive a crash

Atomicity is the property you reach for most often: the guarantee that a multi-step write cannot be left half-done. Isolation is subtler and tunable through isolation levels, which control how much one in-progress transaction can see of another's uncommitted changes -- a topic worth study once concurrency matters.

Rollback preserves the prior state

When a statement inside the transaction fails, rollBack restores every row to its pre-transaction value. Here a CHECK constraint forbids a negative balance, so an over-large debit fails and the whole transfer unwinds.

<?php
declare(strict_types=1);
$pdo = new PDO('sqlite::memory:', null, null, [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
$pdo->exec('CREATE TABLE accounts (name TEXT PRIMARY KEY, cents INTEGER NOT NULL CHECK (cents >= 0))');
$pdo->exec("INSERT INTO accounts VALUES ('alice', 10000), ('bob', 5000)");

function transfer(PDO $pdo, string $from, string $to, int $cents): string {
    $pdo->beginTransaction();
    try {
        $pdo->prepare('UPDATE accounts SET cents = cents - ? WHERE name = ?')->execute([$cents, $from]);
        $pdo->prepare('UPDATE accounts SET cents = cents + ? WHERE name = ?')->execute([$cents, $to]);
        $pdo->commit();
        return 'ok';
    } catch (Throwable $e) {
        $pdo->rollBack();
        return 'rolled back';
    }
}

echo transfer($pdo, 'alice', 'bob', 20000), "\n";
foreach ($pdo->query('SELECT name, cents FROM accounts ORDER BY name') as $r) {
    echo $r['name'], ' = ', $r['cents'], "\n";
}

Output:

rolled back
alice = 10000
bob = 5000

The transfer tries to debit alice by 20000 cents, but she has only 10000, so the CHECK (cents >= 0) constraint rejects the debit and throws. The catch rolls back, and both balances are exactly as they started -- alice 10000, bob 5000 -- with the function reporting rolled back. Without the transaction, alice could have been left with a rejected debit while some later step had already run, corrupting the ledger.

Batches are faster and safer inside a transaction

Beyond correctness, a transaction dramatically speeds up a batch of writes: instead of committing each statement to disk individually, the database commits once at the end. It also makes the batch atomic, so one bad row abandons the whole set. Here a duplicate email violates the primary key partway through, and the entire batch is rolled back.

<?php
declare(strict_types=1);
$pdo = new PDO('sqlite::memory:', null, null, [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
$pdo->exec('CREATE TABLE emails (addr TEXT PRIMARY KEY)');

$batch = ['a@x.com', 'b@x.com', 'a@x.com', 'c@x.com'];
$ins = $pdo->prepare('INSERT INTO emails (addr) VALUES (?)');

$pdo->beginTransaction();
try {
    foreach ($batch as $addr) {
        $ins->execute([$addr]);
    }
    $pdo->commit();
    echo "committed\n";
} catch (Throwable $e) {
    $pdo->rollBack();
    echo "rolled back\n";
}
echo 'rows: ', $pdo->query('SELECT COUNT(*) FROM emails')->fetchColumn(), "\n";

Output:

rolled back
rows: 0

The first two inserts succeed, but the third repeats a@x.com and violates the primary key, throwing. The catch rolls back the entire transaction, so even the two rows that inserted cleanly are undone, and the table ends empty. This is the all-or-nothing property: a batch import either lands completely or leaves the table untouched, never in a partial state that a later run would have to reconcile.


Real World Example: Placing an Order Atomically

Placing an order touches two tables: stock must be debited and the order recorded. These must happen together -- an order with no stock deduction oversells, and a stock deduction with no order loses the sale. Wrapping both in a transaction, guarded by a CHECK on stock, makes the operation atomic and honest.

<?php
declare(strict_types=1);

final class Store
{
    public function __construct(private PDO $pdo)
    {
        $this->pdo->exec('CREATE TABLE stock (sku TEXT PRIMARY KEY, qty INTEGER NOT NULL CHECK (qty >= 0))');
        $this->pdo->exec('CREATE TABLE orders (id INTEGER PRIMARY KEY, sku TEXT, qty INTEGER)');
        $this->pdo->exec("INSERT INTO stock VALUES ('WIDGET', 5), ('GADGET', 2)");
    }

    public function placeOrder(string $sku, int $qty): string
    {
        $this->pdo->beginTransaction();
        try {
            $debit = $this->pdo->prepare('UPDATE stock SET qty = qty - ? WHERE sku = ?');
            $debit->execute([$qty, $sku]);
            $record = $this->pdo->prepare('INSERT INTO orders (sku, qty) VALUES (?, ?)');
            $record->execute([$sku, $qty]);
            $this->pdo->commit();
            return "ordered $qty $sku";
        } catch (Throwable $e) {
            $this->pdo->rollBack();
            return "failed: $sku";
        }
    }

    public function stockOf(string $sku): int
    {
        $s = $this->pdo->prepare('SELECT qty FROM stock WHERE sku = ?');
        $s->execute([$sku]);
        return (int) $s->fetchColumn();
    }

    public function orderCount(): int
    {
        return (int) $this->pdo->query('SELECT COUNT(*) FROM orders')->fetchColumn();
    }
}

$pdo = new PDO('sqlite::memory:', null, null, [
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
]);
$store = new Store($pdo);

echo $store->placeOrder('WIDGET', 3), "\n";
echo 'widget stock: ', $store->stockOf('WIDGET'), "\n";

echo $store->placeOrder('GADGET', 5), "\n";
echo 'gadget stock: ', $store->stockOf('GADGET'), "\n";
echo 'orders recorded: ', $store->orderCount(), "\n";

Output:

ordered 3 WIDGET
widget stock: 2
failed: GADGET
gadget stock: 2
orders recorded: 1

The first order for three widgets debits stock from five to two and records the order, committing both. The second order asks for five gadgets when only two exist, so the debit drives qty negative, the CHECK rejects it, and the transaction rolls back: gadget stock stays at two and no order is recorded. The final tally confirms exactly one order exists, matching the one successful sale. Stock and orders can never disagree, because they move as one unit.

The design flaw appears only under concurrency. Two customers ordering the last widget at the same instant may both read stock as available before either commits, and depending on the isolation level and locking, both debits could apply -- overselling the item. A plain UPDATE ... SET qty = qty - ? guarded by a CHECK protects against going negative in a single transaction, but the deeper race requires either row-level locking (SELECT ... FOR UPDATE) so the second customer waits, or an optimistic-concurrency version column that makes the second commit fail and retry. The transaction guarantees atomicity of these two writes; it does not by itself serialise two independent transactions competing for the same row, and assuming it does is a classic oversell bug.


Common Mistakes

  1. Beginning a transaction and never ending it. An exception that skips both commit and rollBack leaves the transaction open, holding locks. Always end it in a try/catch or finally.
  1. Forgetting to roll back on error. Catching an exception but not calling rollBack leaves the connection in a broken transactional state. Every catch around a transaction must roll back.
  1. Committing partial work by handling errors too early. Swallowing an exception inside the transaction and continuing can commit a half-done change. Let the error propagate to the rollback point.
  1. Nesting beginTransaction calls. PDO does not support true nested transactions by default; a second beginTransaction throws. Use savepoints or restructure so one transaction wraps the work.
  1. Assuming DDL is transactional. In some databases, statements like CREATE TABLE implicitly commit the current transaction. Do not mix schema changes into a data transaction expecting them to roll back.
  1. Relying on transactions to stop overselling. Atomicity is not isolation. Two concurrent transactions can both read stale data; you need locking or a version column to serialise them.
  1. Wrapping read-only work in a transaction needlessly. A pure SELECT rarely needs an explicit transaction. Reserve them for writes that must be atomic, unless you specifically need a consistent snapshot.
  1. Holding a transaction open across slow work. Doing network calls or user prompts inside an open transaction holds locks for a long time, blocking others. Keep transactions short and focused on the writes.
  1. Ignoring auto-commit differences. Outside an explicit transaction, each statement commits on its own. Forgetting this leads to expecting rollback protection you never asked for.

Best Practices

  • Wrap every multi-statement write that must be atomic in beginTransaction, a try with the writes, commit on success, and rollBack in the catch.
  • Keep transactions short: do only the necessary writes inside, and move slow or external work outside the transactional boundary.
  • Re-throw or clearly signal failure after rolling back, so the caller knows the operation did not take effect.
  • Use a transaction to batch many inserts or updates, gaining both atomicity and a large speed-up from the single commit.
  • Reach for row locking (SELECT ... FOR UPDATE) or a version column when concurrent transactions compete for the same rows, since atomicity alone does not serialise them.
  • Keep schema changes out of data transactions, because some databases implicitly commit on DDL.
  • Enforce invariants with database constraints such as CHECK and NOT NULL, so a violated rule triggers a rollback rather than committing bad data.
  • Understand your database's default isolation level, and raise it deliberately only when a specific anomaly demands it.

Practice Exercises

  1. Build two accounts and a transfer function that debits one and credits the other inside a transaction, committing on success. Show the balances after a valid transfer.
  1. Add a CHECK (cents >= 0) constraint and attempt a transfer larger than the balance, proving the transaction rolls back and both balances are unchanged.
  1. Insert a batch of rows inside a transaction where one row violates a unique constraint, and demonstrate that the whole batch is rolled back so the table stays empty.
  1. Simulate an order that debits stock and records an order atomically, then attempt an order exceeding stock guarded by a CHECK, and show that neither the stock nor the orders table changed for the failed order.