What a database is for
Durability, concurrency and queries: the three jobs a file cannot do, and the first one you lose data to
A Python script opens a file, writes 'balance=100', calls file.close(), and prints 'saved'. The machine loses power one second later. When it boots, what is in the file?
A database does three things that a file does not. It makes a committed write survive a crash. It lets many writers work at once without corrupting each other. And it finds rows by what they contain without reading everything. Every database you will ever use is a different set of trade-offs around those three jobs, and every outage you will ever debug is one of them failing.
This chapter makes each job fail with a flat file, then shows what the smallest real database, SQLite, does differently. The rest of the course is the long version of this chapter.
Job one: durability
When a program writes to a file, the bytes go into the kernel’s page cache, a region of RAM that stands in for the disk. The write call returns as soon as the bytes are in that cache. The kernel flushes dirty pages to the disk on its own schedule, which on Linux defaults to within about 30 seconds, or sooner if memory is tight.
That means “the write returned” and “the write is on disk” are different events separated by up to half a minute. If the process crashes in between, the data is fine: the kernel still has it and will flush it. If the machine loses power or the kernel panics, the data is gone.
To close the gap a program calls fsync(fd). That blocks until the device confirms the bytes are on stable storage. On a modern SSD it takes 100 microseconds to a few milliseconds. On a spinning disk it takes 5 to 10 milliseconds because the head has to move. Some consumer drives lie about it and acknowledge before the data is in non-volatile memory, which is a separate problem that enterprise drives with power-loss protection solve.
There is a second problem. Even with fsync, a write of more than one sector is not atomic. A 4 KB page is eight 512-byte sectors, and a power cut can land between them. The file ends up with half the old page and half the new one, which is called a torn write. No amount of fsync prevents it. Durability needs a protocol, not a flag.
The protocol every database uses is the write-ahead log. Before changing any data page, the engine appends a description of the change to a sequential log file and fsyncs the log. Only then does it modify the page, and it can do that lazily. If the machine dies at any point, recovery reads the log: every change whose log record is complete is redone, every incomplete transaction is undone. The log record itself has a checksum so a torn log write is detected and discarded. You will meet this protocol in depth in the chapter on write-ahead logging and again, formally, in ARIES.
SQLite does this with a rollback journal by default, or a WAL in WAL mode. A COMMIT in SQLite is one or two fsyncs. That is why SQLite can promise what your Python script cannot, and why a loop that commits one row at a time runs at a few hundred rows per second on a laptop while the same loop inside one transaction runs at hundreds of thousands.
Job two: concurrency
The second thing a file cannot do is let two writers work at once.
Suppose the stock count for a product lives in a file: the text stock=5. Two workers each receive an order. Each reads the file, sees 5, subtracts one, and writes stock=4. The shop has sold two items and recorded one. This is a lost update, and it is the same bug the data-race lesson shows between two threads, only slower and with a file instead of a register.
The file system gives you no atomic read-modify-write. You can add a lock file, and now you have to handle a worker that crashes while holding it. You can use flock, which does not work on every network file system and which every reader and writer has to remember to call. You can rename a temp file over the original, which gives you atomic replacement of the whole file but not atomic update of one field while another process updates a different one.
A database solves this with transactions. A transaction is a group of reads and writes that the engine promises to run as if it were alone. Inside one, you read the stock, decide, and write, and the engine makes sure another transaction cannot slip a write in between. How it does that is the single largest topic in this course: locks, multi-version concurrency, snapshot isolation, and the catalogue of anomalies that leak through when the isolation level is weaker than you assumed. For now the point is that the problem exists the moment you have two writers, and a file hands it to you unsolved.
SQLite’s answer is blunt: one writer at a time, database-wide. A second writer waits or gets SQLITE_BUSY. That is correct and it is also why SQLite is the wrong choice for a busy multi-writer service, which the Decide below turns into a real choice.
Job three: queries
The third job is finding things. A directory of JSON files answers “give me order 4521” fast, because the file name is the key. It answers “give me every order over 100 euros shipped to Berlin in March” by opening every file. At ten thousand orders that is a second. At ten million it is an hour, and the loader that does it holds a lock the whole time, which brings back job two.
A database keeps indexes: separate structures, usually B+ trees, sorted by a column, so a query on that column reads a few pages instead of all of them. It also has a query planner that looks at a declarative question (SQL says what, not how), estimates how many rows each strategy would touch, and picks the cheapest. The chapters on indexes and the planner cover both. The practical consequence today is that a well-indexed query over ten million rows takes a millisecond, and a badly indexed one takes a minute, and the SQL text is identical. Making the difference visible is what EXPLAIN is for and you will use it in the lab.
What a database is not for
Durability, concurrency and queries are expensive. Each fsync costs a disk round trip. Each transaction costs bookkeeping. Each index costs space and slows every write that has to maintain it. When you do not need one of the three, you pay for it anyway, and sometimes a file is right.
A build cache does not need durability: if it is lost, you rebuild it. A log file that is appended by one process and read by another needs no transactions. A configuration file that changes once a month needs no indexes. Static assets, large media, and backups belong in object storage, not in a database row. Knowing which of the three jobs you actually need is the first database decision, and the later chapter on choosing a database formalises it.
The shape of the course
Everything after this chapter is one of these three jobs, examined closely:
- Durability becomes the write-ahead log, checkpoints, crash recovery, backups and point-in-time recovery, replication, and eventually the disaggregated storage behind Aurora and Neon.
- Concurrency becomes transactions, isolation levels and their anomalies, MVCC and vacuum, locking and deadlocks, distributed transactions, and the consistency models of distributed stores.
- Queries becomes the relational model, SQL, indexes, the planner, columnar storage, search engines, and the specialist engines for graphs, time series and vectors.
A database that is good at one job is often weak at another: a key-value store answers point lookups in microseconds and cannot run a join; a columnar warehouse scans a billion rows in a second and takes a second to insert one. The decision framework in module three is built on this triangle.
You will break durability and concurrency with a flat file, then watch SQLite refuse to break. Work in an empty directory.
1. A write that is not durable.
Create write.py:
import os, sys
with open("balance.txt", "w") as f:
f.write("balance=100\n")
if "--fsync" in sys.argv:
f.flush(); os.fsync(f.fileno())
print("saved")Run it, then immediately read the file:
python3 write.py && cat balance.txtsaved then balance=100. Of course it reads back: you are reading from the same page cache the write went into. A real power cut is the only honest test, and you cannot run one here. The next step shows the gap in time instead.Measure when the bytes actually reach the disk. On Linux, grep Dirty /proc/meminfo before and after the write shows kilobytes waiting to be flushed; run it in a loop and watch the number fall back after up to 30 seconds. On macOS the closest view is sudo fs_usage -f diskio | grep balance, which shows the write to the device arriving well after the script has exited. Now run with --fsync and the disk write appears before saved is printed.
Time the difference over a thousand writes:
python3 - <<'PY'
import os, time
def run(fsync):
t = time.perf_counter()
for i in range(1000):
with open("balance.txt", "w") as f:
f.write(f"balance={i}\n")
if fsync: f.flush(); os.fsync(f.fileno())
return time.perf_counter() - t
print(f"no fsync: {run(False):.3f}s fsync: {run(True):.3f}s")
PYno fsync: 0.02s fsync: 2.1s on a laptop SSD, so about 2 ms per fsync. On a spinning disk the second number is 5 to 10 seconds. That gap is the price of durability, and every database you will ever tune is finding ways to pay it less often.2. A lost update.
Create stock.py, which simulates two order workers:
import sys, time
from multiprocessing import Process
def worker(n):
for _ in range(n):
with open("stock.txt") as f: v = int(f.read())
time.sleep(0) # yield, like a real worker would
with open("stock.txt", "w") as f: f.write(str(v - 1))
open("stock.txt", "w").write("10000")
ps = [Process(target=worker, args=(1000,)) for _ in range(2)]
[p.start() for p in ps]; [p.join() for p in ps]
print("expected 8000, got", open("stock.txt").read())python3 stock.pyexpected 8000, got 8973 or some other number above 8000, different every run. Each number above 8000 is a sale that happened and was not recorded. Run it three times; it never agrees with itself.3. The same two jobs in SQLite.
sqlite3 shop.db "create table stock(id integer primary key, n integer); insert into stock values (1, 10000);"Create stock_db.py:
import sqlite3
from multiprocessing import Process
def worker(n):
db = sqlite3.connect("shop.db", timeout=30, isolation_level=None)
for _ in range(n):
db.execute("begin immediate")
(v,) = db.execute("select n from stock where id=1").fetchone()
db.execute("update stock set n=? where id=1", (v - 1,))
db.execute("commit")
ps = [Process(target=worker, args=(1000,)) for _ in range(2)]
[p.start() for p in ps]; [p.join() for p in ps]
import sqlite3 as s; print("got", s.connect("shop.db").execute("select n from stock").fetchone()[0])time python3 stock_db.pygot 8000, every time. And it takes a few seconds: 2000 commits, each with its fsync, which is step 1’s price showing up again. begin immediate takes the write lock before the read so the read-then-write is one unit; try changing it to a plain begin and the second worker gets SQLITE_BUSY on its update instead of a wrong answer. SQLite would rather fail loudly than lose a write.4. Queries. Load a hundred thousand rows and compare a scan with an index:
sqlite3 shop.db <<'SQL'
create table orders(id integer primary key, city text, total integer);
with recursive n(i) as (select 1 union all select i+1 from n where i<100000)
insert into orders select i, case i%5 when 0 then 'Berlin' when 1 then 'Lagos' when 2 then 'Lima' when 3 then 'Osaka' else 'Oslo' end, (i*7919)%500 from n;
.timer on
select count(*) from orders where city='Berlin' and total>400;
explain query plan select count(*) from orders where city='Berlin' and total>400;
create index orders_city_total on orders(city, total);
select count(*) from orders where city='Berlin' and total>400;
explain query plan select count(*) from orders where city='Berlin' and total>400;
SQLSCAN orders; the second says SEARCH orders USING COVERING INDEX orders_city_total (city=? AND total>?). The count is the same both times. The time drops from a few milliseconds to well under one; at ten million rows the first number would be seconds. The chapter on indexes explains why the column order in that index matters.fsync from stock_db.py’s connection by running sqlite3 shop.db "pragma synchronous=off" inside the worker before the loop, re-run, and time it: commits get 10 to 50 times faster and the result is still 8000, because concurrency is handled by locks, not by fsync. What you have given up is only visible on a power cut, which is exactly why teams turn this knob and do not notice until the day they do. Then open a second terminal, run sqlite3 shop.db "begin immediate; select 1;" and leave it open while re-running stock_db.py: both workers block for 30 seconds and then fail with “database is locked”. One idle writer stops the whole database. That is the single-writer trade-off, and the Decide below is about it.You are building a small internal tool: a web app that 30 colleagues use to book meeting rooms. One server, one process, under 10 writes per second at peak, and the data must not be lost. A colleague proposes SQLite; another says 'use Postgres, it is what real systems use'. What do you pick?
- BOOK Designing Data-Intensive Applications Martin Kleppmann, 2017
The best single book on this course's subject. Chapter 1 defines reliability, scalability and maintainability, which map onto the three jobs here; chapter 3 is the storage engines you meet in module 2. Read: chapters 1 and 3 now; the rest as the course reaches them.
- DOC SQLite: How It Works (Architecture)
A one-page tour of a complete database engine: tokenizer, parser, code generator, virtual machine, B-tree, pager, OS interface. Every later chapter is an elaboration of one box in this diagram.
- DOC Atomic Commit In SQLite
The clearest written account anywhere of how a commit becomes durable: which bytes are written in which order, where each fsync goes, and what recovery does after a crash at each step. Read it before the WAL chapter.
- POST Files are hard Dan Luu, 2015
A survey of how real programs misuse the file API and lose data, with the research that found the bugs. Makes the case that you should not write your own durability.
- PAPER All File Systems Are Not Created Equal: On the Complexity of Crafting Crash-Consistent Applications Pillai et al., 2014
The study behind Dan Luu's post. Shows that databases and version control systems, written by experts, still had crash-consistency bugs that depended on which file system they ran on. Read: sections 1 to 3 and the table of application bugs in section 4.
- POST Long-term SQLite usage in production David Crawshaw, 2021
A working engineer's account of where SQLite is the right choice and how far one process gets you. Pairs with the Decide above.
All companies and people in these examples are fictional. Any resemblance to a real business or person is unintended.