A transaction groups statements into one unit of work. ACID properties ensure that either all required changes commit together or none do, preserving data integrity under failure and concurrency.
- Use BEGIN and COMMIT around related writes that must succeed together.
- Pick isolation levels based on correctness needs and concurrency cost.
- Handle rollback paths explicitly in application and job code.
Model one business action as one transaction
At Northstar, placing an order can require creating the order row, inserting line items, recording payment intent, and decrementing inventory. If one step fails, partial writes create cleanup debt and customer confusion.
Wrapping these writes in a transaction keeps the system consistent: either the action finishes fully or it rolls back.
Understand isolation and conflict behavior
Concurrent updates can create anomalies such as lost updates or inconsistent reads. Isolation levels define which anomalies are allowed and which are prevented.
Higher isolation can increase lock contention, so teams should choose the minimum level that still protects correctness for the operation.
- Keep transactions short to reduce lock duration.
- Retry safely on serialization or deadlock errors.
- Log transaction failures with enough context for support follow-up.
Reserve stock and create order atomically
Checkout writes to orders, order_items, and inventory for the same basket in one request.
- BEGIN transaction and lock relevant inventory rows for selected SKUs.
- Insert order and order_items, then decrement available quantity only if stock is sufficient.
- COMMIT on success, or ROLLBACK when any write or stock check fails.
Common mistakes
- Running related writes outside a transaction boundary.
- Keeping transactions open across slow network calls.
- Ignoring retry logic for transient concurrency failures.
- Assuming default isolation always protects against lost updates.
Try one
Why should payment record creation and inventory decrement be in the same transaction?
They represent one business action; committing one without the other can leave the system inconsistent.
Sources
- PostgreSQL 18 Docs: TransactionsOfficial PostgreSQL transaction control and commit or rollback behavior.