Lesson 2 of 19
17. Transactions and Locking

17.1 What is a transaction?

3 min read+10 XP

Transactions

On the train: A ticket isn't "a seat" plus "a payment" done separately. If the payment fails, you don't keep the seat. If the seat is gone, you aren't charged. It's one deal.

In the system: A transaction is a group of database operations that succeed or fail as one unit:

sql

If anything fails in between (a constraint, a crash, a deliberate ROLLBACK), the database undoes the whole group. You never end up with a sold seat and no payment, or the reverse.

Two practical rules:

  • Keep transactions short. A transaction holds locks (17.6) until it ends. Never wait for a user, an email or a slow external API inside one.
  • Be ready to retry. The database may abort a transaction because of a conflict or deadlock (17.8). Well-written code retries the whole transaction.

Memory code: "Seat and payment, together or not at all."