Atomicity

All or nothing transactions

“Atomicity requires that each transaction is ‘all or nothing’: if one part of the transaction fails, the entire transaction fails, and the database state is left unchanged.”

When to use

Financial transactions, Inventory updates, multi-step writes.

Why it matters

  • Integrity: Prevents partial data states (e.g., Money deducted from Sender but not added to Receiver).

Signs of Violation

  • Creating an Order record, then crashing, leaving the Order without Line Items.
  • Orphaned rows in the database.

Explanation

Problem

If you have 3 steps (Debit A, Credit B, Log Transaction), and step 2 fails, you corrupted the data.

Solution

Wrap them in a Transaction. If anything fails, Rollback everything to the start state.

Real world analogy

Buying a soda from a vending machine. You put money in. You press the button. The machine jams. Atomicity means the machine gives you your money back (Rollback). It doesn’t keep the money AND give you no soda (Partial failure).

Pros and Cons

Pros Cons
  • Data Safety
  • Performance overhead (Locking)
  • Comparison

    • Sagas: The microservices equivalent of Atomicity (using compensating transactions) where strict DB transactions aren’t possible.

    Code example

    Typescript

    Bad (Violation)

    Good (Adherence)

    PHP

    Bad (Violation)

    Good (Adherence)