Transactions

All together or nothing · Part of Databases

Key idea

Practice

6 questions · about 3 min

Explained step by step

Transaction

A transaction is a series of database operations treated as a single unit of work: either all succeed, or all fail. That way data stays intact even if part of the system fails halfway. It's like buying a round-trip ticket: either you have both legs, or you have neither and get your money back. A transfer has 2 operations: subtract $100 from one account and add it to another.

A transaction goes through states. It starts active, while it runs. When it runs its final operation it's partially committed. If everything went well it's committed, and its effects are permanent. Finally it's terminated and the system is ready for the next one. It's like a shipment: being prepared, dispatched, delivered and closed.

A transaction is terminated when it leaves the committed state, or when there was nothing to undo. At that point the system is consistent and ready for a new transaction. There are 2 paths to get there: the happy one (active, partial, committed, terminated) and the error one (active, failed, aborted). It's like closing the till at the end of the day: everything balances and tomorrow's can open.

ACID

Not every database supports ACID transactions, usually because it prioritizes other things, like scaling, that are hard or impossible to achieve at the same time. Generally, relational databases support ACID transactions and non-relational ones don't, though there are exceptions. It's like paying at a bank versus paying at a street market: the bank gives you a receipt and guarantees; the market is faster but informal.

Commit

A transaction is committed when it ran all its operations successfully. From then on, all its effects are permanently established in the database. It's like signing a deed: until you sign, you can back out; afterwards, the house is yours. If 3 operations succeeded and the commit happened, all 3 are saved for good.

Rollback

If any check fails, the transaction becomes failed and can't continue. Then the recovery system does a rollback: it undoes all its writes to leave the database as it was before it started. The transaction is then aborted. It's like an editor's 'undo' button: everything goes back to the starting point. If a transaction wrote 2 of 3 changes and fails, those 2 are erased.

After aborting a transaction, the recovery module can choose between 2 paths: restart it, to try again from scratch, or kill it, discarding it for good. Restarting works if the error was temporary, like a momentary lock. Killing works if it will never succeed, like invalid data. It's like a dropped call: if it was the signal, you call again; if the number doesn't exist, you don't keep trying.

Terms in this lesson

Arki, the beaver mascot

Your next interview starts with 5 minutes today.

Free on iOS and Android. Start from zero, no account needed.

Key idea

All together or nothing