Kit (Phuc) Nguyen

How Databases Actually Work, Part 2: Keeping Your Data Safe

Nov 29, 2026 · databases

Picking up where Part 1 left off

In Part 1, we followed one query, SELECT * FROM players WHERE name = 'Kit', through a database. The table lives on disk as a heap of fixed-size pages, the buffer cache keeps the busiest pages in RAM, a B-tree index takes us to Kit’s row in about four page reads, and the planner decides how to run the query in the first place.

All of that was about reading data. This part is about changing it safely. When a player picks up a diamond, the database has to record it in a way that survives a crash, while thousands of other players are reading and writing the same tables at the same time. We’ll stick with the same Minecraft server: a players table, an inventory table showing what each player is carrying, and a trades table where players swap items.

What if the server crashes?

Say a player picks up a diamond. The server runs an UPDATE, and the database replies “done”. From that moment, the player expects the diamond to stay in their inventory, even if the server crashes a second later.

Postgres could write the changed page to the heap on disk before replying, but then every update would have to wait on slow disk writes. Instead, it changes the page in RAM, in the buffer cache, and saves it to disk later. That’s fast, but RAM is wiped in a crash. If Postgres replied “done” with the change only in RAM and then crashed, the diamond would vanish. So before replying, it needs to save something to disk, something much cheaper to write than the page itself.

The answer is a separate file on disk called the write-ahead log, or WAL. Before replying “done”, Postgres adds a short note describing the change to the end of the WAL: “player 42: diamonds 5 → 6”. It’s called write-ahead because each change is written there ahead of the actual data. If the server crashes, Postgres reads the WAL back and redoes any change that hadn’t reached the heap yet.

But isn’t writing to the WAL just as slow as writing to the table? Not really, because one disk write to the WAL can cover many changes.

Suppose Kit earns 10 XP and Alex earns 20 XP. Their rows live on different pages in the table, so writing both changes directly to disk would mean writing two separate pages, even though only one number changed on each. Instead, the database leaves those modified pages in memory and appends a short WAL record for each update. Because the records are written back-to-back, dozens of small updates fit in a single WAL page, and one disk write saves all of them. It helps, too, that new records always go at the end of the WAL, in one spot, while table pages are scattered across the disk. The database writes the table pages later, and if it crashes first, it replays the WAL to recover the updates.

The pages still get written eventually, just later, in the background, where ten changes to the same page can be saved in one go.

So why update the page in RAM at all, if the change is already in the log? Because the WAL is only a list of notes, not something you can search. When another player checks the inventory a second later, Postgres needs the actual page with the up-to-date row, and the fastest place to get it is the buffer cache. The page in RAM is what queries use; the WAL is only read back after a crash, to rebuild whatever was lost from RAM.

Putting it all together, here’s the full sequence for UPDATE inventory SET diamonds = diamonds + 1 WHERE player_id = 42:

  1. Change the page in RAM. Postgres updates the page in its buffer cache, so any query that comes in next reads the new value straight from RAM. (This is Postgres’s own memory. The operating system doesn’t see the change until Postgres writes the page out.) The copy on disk still has the old value, so Postgres marks the copy in RAM as “dirty”: a flag meaning this page has changed but hasn’t been saved to disk yet.

  2. Append a note to the WAL. A short description of the change (“player 42: diamonds 5 → 6”) is added to the end of the log.

  3. Save the WAL to disk when the change commits. A single statement like this one commits automatically (more on commits below). At that point, Postgres makes sure the WAL has actually reached the disk (this is called flushing the WAL), rather than just handing it to the operating system, which can hold writes in RAM for a while before saving them. Only then does it reply “done”. That one write is what makes the change permanent. If other players commit at the same moment, their notes go out in that same write, so one disk write can confirm dozens of changes at once.

    What if the server crashes in the middle of that write? Then Postgres never replied “done”, so nobody was told the change succeeded. On restart, it spots the half-written note (every note carries a checksum) and simply ignores it.

  4. Write the data pages later. Every so often, at a checkpoint, Postgres writes all the dirty pages back to the data files. If a page changed ten times since the last checkpoint, that’s still just one write.

If the server crashes after step 3 but before step 4, nothing is lost. On restart, Postgres goes back to the last checkpoint, the last moment all dirty pages were safely written, and replays the WAL from there, redoing every change that hadn’t reached the data files yet. A change whose commit never made it into the log is treated as if it never happened.

Animated write path: the page changes in RAM, the WAL record is flushed to disk at commit, a crash wipes RAM, and replaying the WAL restores the change
The data file never gets the new value before the crash. The WAL on disk is what brings it back.

Trading safety for speed

Step 3 is the slow part of every commit: Postgres waits for the disk to confirm the WAL write before it replies “done”. For a diamond trade, that wait is the whole point. For a chat message, it might not be worth it. If a crash loses the last few messages, nobody minds much.

For data like that, you can turn on asynchronous commit, meaning the reply no longer waits for the disk. Postgres replies “done” right after step 2, while the note is still in RAM, and saves the WAL to disk a fraction of a second later in the background. Commits get much faster, but there’s a short window where the player has been told “done” and the note isn’t on disk yet. If the server crashes in that window, those last few changes are lost.

What you won’t get is a broken database. The WAL on disk is still complete up to a point, so on restart Postgres replays it as usual and ends up where it was a moment before the crash, just missing the newest changes. And you can switch it on per transaction, so chat messages skip the wait while trades still get it.

Bonus: the WAL is how replication works

Because the WAL records every change in order, a second server can stay up to date by receiving the main server’s WAL notes as they’re written and replaying them on its own copy of the data, just like Postgres does after a crash. This is called replication. The copy can’t accept writes of its own, but it can answer read-only queries to share the load, and take over if the main server dies. It usually runs a fraction of a second behind, since the notes take a moment to arrive.

Replication is especially useful for AI agents, because agent workloads are read-heavy. To answer one request, an agent might run dozens of queries, such as fetching a user’s history, looking up relevant documents and checking the state of a task, while writing far less often. So a common setup is one main server that handles every write, plus a few copies, called read replicas, that share the reads. If the agents need more capacity, you add another replica. Because of that small delay, if an agent writes something and reads it straight back, that read should go to the main server.

Many users at once

Thousands of players read and write at the same moment, and that raises two problems. Take a trade where Kit gives Alex 3 diamonds. First, that’s more than one change: Kit’s diamonds go down and Alex’s go up, and both have to happen or neither. Second, other players keep reading while the trade runs. Someone who looks between those two changes would see 3 diamonds gone from Kit but not yet with Alex. They shouldn’t see that, and they shouldn’t have to wait for the trade to finish either. Postgres solves the first with transactions and the second by keeping more than one version of each row. Let’s take them one at a time.

A trade, and why it needs a transaction

Kit gives Alex 3 diamonds for 1 elytra. That’s four changes, and they have to happen together or not at all. That’s exactly what a transaction is: a group of changes wrapped in BEGIN and COMMIT that the database treats as one. Running COMMIT (“committing”) is how a transaction says “I’m done, make it all permanent”: Postgres saves the changes to the WAL on disk, and from then on other queries can see them. Until that moment, the changes are only provisional. If something fails halfway, or you run ROLLBACK, they are all undone as if they never happened.

BEGIN;
UPDATE inventory SET diamonds = diamonds - 3 WHERE player_id = 1; -- Kit
UPDATE inventory SET diamonds = diamonds + 3 WHERE player_id = 2; -- Alex
UPDATE inventory SET elytra = elytra - 1 WHERE player_id = 2;
UPDATE inventory SET elytra = elytra + 1 WHERE player_id = 1;
COMMIT;

Transactions come with four guarantees, known as ACID:

Letter Promise In the trade
Atomicity All of it happens, or none of it No diamonds vanish if the server crashes halfway
Consistency Rules always hold A rule like CHECK (diamonds >= 0) stops Kit trading diamonds they don’t have
Isolation Nobody sees a half-finished change No other player sees Kit’s diamonds gone before Alex has them
Durability Committed means permanent Once committed, the trade survives a crash, thanks to the WAL

Readers and writers don’t block each other

Back to the trade. Kit has 10 diamonds, and the trade is about to take 3. While it runs, another player opens Kit’s inventory. They should see 10, because the trade hasn’t finished. Once it commits, everyone should see 7.

Postgres handles this by never overwriting a row in place. When the trade updates Kit’s row, Postgres adds a new version of it (7 diamonds) and keeps the old version (10 diamonds) too. For a moment, Kit’s row exists twice, and each query reads whichever version it should see, without waiting. Keeping several versions of a row like this is called multi-version concurrency control, or MVCC.

So how does a query know which version to read? This is where transactions come back in. Every change in Postgres happens inside a transaction, even a lone UPDATE, which Postgres automatically wraps in its own BEGIN and COMMIT. Each transaction that changes data gets its own number, called a transaction ID. Say the trade’s transaction ID is 101. When the trade changes Kit’s row, Postgres writes 101 on both versions. On the new one, it means “transaction 101 created me”. On the old one, it means “transaction 101 replaced me with a newer version”. The two labels are called:

A query can start while the trade is still running, so which version should it read? The rule is: a query only sees changes from transactions that had already committed when the query began. Anything that commits after that stays invisible to it, so it never mixes rows from before the trade with rows from after. For Kit’s row, that means:

Two versions of Kit’s row stored at once: the old version with 10 diamonds and xmax = 101, and the new version with 7 diamonds and xmin = 101. Query A starts before transaction 101 commits and reads 10; Query B starts after and reads 7. MVCC row versions in Postgres · illustrative transaction IDs

Because each query just picks the right version, reading never has to wait for a change to finish, and a change never has to wait for readers. Someone can check Kit’s inventory in the middle of the trade and get an answer straight away, while the trade carries on.

The one time something does have to wait is when two transactions change the same row. Say Kit starts a second trade, giving 2 diamonds to Sam, while the first is still running. Both want to change Kit’s diamonds, so the second trade waits for the first to commit and bring Kit down to 7, then takes its additional 2 from there.

Animation: the trade (transaction 101) adds a new version of Kit's row with 7 diamonds while keeping the old one with 10. Query A starts before the trade commits and reads 10; Query B starts after the commit and reads 7.
Same row, two versions: each query sees the one that was current when it started.

The catch: dead rows and bloat

Once the trade has committed and Query A has finished, nobody will ever read the old 10-diamond version of Kit’s row again, but it still takes up space on its page. That’s a dead row. Every update leaves one behind, so in a busy table, live rows end up spread across far more pages, and every query has to read more of them. That’s called bloat.

There are two ways to clean up:

Isolation levels

What happens if your transaction is still running, and another one finishes in the middle of it?

Say your transaction checks Kit’s diamonds, does some other work, then checks them again. In between, the trade (a separate transaction) commits and takes 3 of Kit’s diamonds. Should your second check see the 10 that were there when your transaction started, or the 7 that are there now? Postgres lets you choose, and that choice is the transaction’s isolation level. There are three:

The stricter the level, the more often Postgres cancels a transaction, and your app has to retry it. So most apps keep the default and switch only for the transactions that really need it.

Same problems, different trade-offs

Every database is solving the same problems: storing data, finding it quickly, not losing it, and handling many users at once. What makes them different is which problem each one is willing to make worse to make another one better. Now that you’ve seen how Postgres handles each one, the others are easy to place.

Postgres: the do-almost-everything default

Postgres is the engine we’ve been taking apart: a heap of pages, B-tree indexes, a WAL and MVCC. It’s the default choice for most apps because it’s open source and free to use, very reliable, and good at a wide range of jobs. You can also add extensions to support new data types and new ways of searching them, while keeping the same SQL and transactions:

Redis: give up disk, gain speed

Redis keeps everything in RAM, so with no pages to fetch from disk, most operations finish in well under a millisecond. There are no tables either: it works like one giant hash map, where every piece of data is stored under a key.

The catch is that all your data has to fit in RAM, and saving it to disk is optional. By default, Redis only saves a full copy of the data every so often, so a crash can lose minutes of writes. You can make it save after every write, but then every write waits on the disk and Redis loses much of its speed. That makes it great for things you can rebuild if they’re lost, like caches, login sessions and leaderboards, and a bad home for the only copy of player trades.

MongoDB: give up easy joins, gain flexible documents

MongoDB stores each record as a document: a nested, JSON-like object. Kit’s profile, settings and inventory can all live in one document and be read in one go, with no joins. Documents don’t need a fixed schema, so you can add new fields without changing a table, and MongoDB is built to spread data across many servers (sharding).

The catch is anything that spans documents. A trade changes both Kit’s and Alex’s documents. MongoDB can update both in one transaction, but it’s slower and more limited than in Postgres, and combining documents is clumsier than a SQL join. That makes it a good fit for data that’s naturally one document per thing, like player profiles, and a worse one for data full of relationships, like trades.

Wrapping up

The short version: start with Postgres. Add Redis when something has to be faster than disk allows. Reach for the others only when a specific limit forces your hand. And next time a query comes back in 2 milliseconds, or a commit survives a crash, you’ll know how much happened in that blink.

That was a lot, and if parts of it felt convoluted, that’s normal. Pages, logs, row versions and snapshots are a lot to hold in your head at once, and most of it only really clicks once you run into it in your own work.

And you will run into it. RAG and GraphRAG rely on indexes to find the right data quickly, agents depend on read replicas to keep up with their queries, and everyday apps run on B-trees, the WAL and MVCC without you ever noticing. Each time you meet one of these again, it’ll make a bit more sense.

I’m not sure yet what I’ll write about next. A few ideas: how agent memory works and the different approaches for it, how agent frameworks compare and what their abstractions hide, or how transactional databases and star schemas work. If you enjoyed this, or there’s something you’d like me to cover, let me know.

Back to all writing