It sounds like this“When my program saves a file, the save either happens completely or not at all.”
Thinking saving a file is all-or-nothing
Why it feels right
Saving feels instant. You press the button, the icon flashes, and it is done. It is natural to picture the file as switching from the old version to the new one in a single click, like a light, with nothing in between.
Why it’s wrong
A write takes time and can be cut short. A crash or power cut in the middle can leave a file that is half new and half old, or empty. A transaction makes a group of changes all-or-nothing, and a database recovers to a clean state after a crash.
A worked example
Writing a file is really a series of small writes to a disk, one block at a time. If the power cuts out half way, some blocks are new and some are old. The result might be a file that doesn't open, one that has a half-finished record at the end, or one with zero bytes in it.
It gets worse when one job needs two writes. Moving 50 from account A to account B means subtracting 50 from A and adding 50 to B. If A holds 100 and B holds 0, and the crash comes between the two steps, A has 50, B has 0, and the 50 has vanished: the total has dropped from 100 to 50.
A database groups the two steps into a transaction and writes a journal first, so that after a crash it can either finish the job or undo it. The promise is called atomicity: all the steps happen or none do. It is one of four guarantees summed up as ACID.
How to catch yourself
- You trust that a save is complete if the program says it saved.
- You keep related data in two files and update them one after another.
- You have no plan for what happens if the machine loses power mid-write.
What to hold instead
A save takes many small steps and can be cut short, leaving damaged or half-updated data. A transaction makes several changes all-or-nothing, and a database uses a journal to recover to a clean state after a crash.
Where you’ll meet it
- Moving money, stock or points between two records.
- Wondering why a file is empty after a crash.
- Choosing between a file and a database for important data.
Questions people ask
- What does atomic mean in a database?
- That a transaction's changes happen entirely or not at all. If a crash interrupts it, the database undoes the partial work, so you never see half of a transfer.
- Can a file be corrupted by a power cut?
- Yes. If the machine stops while a file is being written, it can be left with some old and some new data, or empty. Databases use journals so they can recover.