Postgres transaction pattern with pgx: defer rollback, commit explicitly

13229
0

The most common transaction bug I see is forgetting to roll back on early returns. With pgx, I like the “defer rollback” pattern: start the transaction, defer tx.Rollback(ctx), then call tx.Commit(ctx) only on success. Rollback after a successful commit is a no-op, so the defer is safe and removes a whole class of mistakes. I also keep DB calls scoped to ctx so cancellations stop long queries. When multiple writes must be atomic (create row, insert audit log, upsert index table), this pattern keeps the failure modes simple. It’s boring code, which is exactly what you want for money, permissions, and idempotency state.