Keep a database operation all-or-nothing
Place transaction boundaries around one business invariant.
Define the unit of work
Creating an invoice and its ledger entry is one operation if either record is meaningless alone. Start a transaction before the first write, commit after the last, and roll back when an invariant or database call fails. Keep network calls outside the transaction so a slow service does not hold database locks.
Handle concurrent requests
A transaction does not by itself prevent two requests from both passing a pre-check. Add a uniqueness constraint or lock the row that represents scarce state. Retried operations should carry a stable key so a duplicate request can return the first result instead of writing twice.
with connection:
insert_invoice(connection, invoice)
insert_ledger_entry(connection, invoice.id, amount)
Test rollback
Force the second write to fail and verify that the first record is absent. Test a duplicate request and a competing request when the database engine supports a realistic concurrency check. A test with only the happy path proves little about transaction placement.
Check your understanding
Why can two transactions still create duplicate work after both pass a read check?
Show explanation
The read-check-write sequence can race. Enforce uniqueness or locking in the database and make retries idempotent.
You can read for free. Create an account to save your progress.
← Previous lesson: Write tests for rejected and duplicate work Next lesson: Build tests that explain behavior →Put this lesson into practice
A practice activity at this level in the same module.
Try: Fix a SQL injectionFurther reading
Primary references for this module. Check the current version when behavior or framework guidance may have changed.