A transaction groups related database changes into one logical operation. If a critical step fails, the transaction can be rolled back so partial changes are not committed.
The normal flow is begin → perform operations → commit on success → rollback on failure.
Deep dive
When to use transactions
Use a transaction when multiple database changes must either all succeed or all fail. Examples include transferring money, creating an order with inventory changes, or updating related records.
Keep transactions short
Do not perform slow external network calls inside a database transaction unless the design specifically requires it. Long transactions can hold locks and reduce concurrency.