Almost every system on this site keeps its truth in a database: orders, balances, posts, who follows whom. The database is usually the hardest part to scale and the one part you cannot lose, so most of its behaviour is about doing work safely when many people ask at once.
This page takes the questions that come up in real incidents one at a time: why one query is slow, why the app runs out of connections, why two updates block each other or quietly cancel out, why a page shows old data, and what is lost when a server dies.
Each lab after the walkthrough is a small simulation running in your browser, with time slowed down so you can follow each query. A green chip such as #12 is a read, a yellow +3 is an insert. Click any moving item to follow it and see what happened to it.
00 The life of one write
Before the live labs, follow a single change from the app to the disk and on to a replica. Step through at your own pace, or press Play all.
Step 1 of 9
Meet the pieces
Your code runs on an app server, which keeps a few open connections to the database in a pool. Inside the database, the users table holds the rows, an index finds them fast, and the write-ahead log records every change in order. A replica keeps a copy for reads.
01 Indexes: reading one row, not all of them
A table is stored as pages of rows in no useful order. To answer WHERE email = 'u48213@x.io' without help, the database must read every row and check it. That is a sequential scan, and its cost grows with the table.
An index is a second structure, usually a B-tree, that keeps the emails sorted with a pointer to each row. Each page of the tree holds hundreds of keys, so even a table of a million rows is only three levels deep. A lookup reads the root, one branch, one leaf and then the row: four pages instead of a million rows.
- Waiting
- 0
- Rows examined
- 0
- Lookup time
- 0 ms
Click any query chip to follow that one query.
When a query is slow, run EXPLAIN ANALYZE and look for a sequential scan on a big table. An index on the column you filter by is the most common fix in all of database work.
02 What every index costs
Indexes are not free. Every insert writes the row to the table and an entry to every index on that table. Updates that change an indexed column and deletes pay too. Indexes also take disk space and memory that the hot data could have used.
- Waiting
- 0
- Writes per insert
- 2
- Insert time
- 0 ms
Click any query chip to follow that one query.
Index what your queries filter and sort by, and drop indexes nothing uses. Read-heavy tables can afford many; write-heavy ones cannot.
03 Connection pools
Opening a database connection is slow: a network handshake, often TLS, authentication, and in PostgreSQL a whole new server process. So each app server opens a few connections at startup and keeps them in a pool. A request borrows a connection, runs its queries and gives it back.
The pool has a fixed size. When every connection is busy, the next request waits in line, and if it waits too long the pool gives up with a timeout error.
- Served
- 0
- Failed
- 0
- Wait for a connection
- 0 ms
- Response time
- 0 ms
Click a waiting request (yellow square) or a busy connection (orange) to follow that request.
- 1 app server × 3 = 3 of 40 database connections.
“Timed out waiting for a connection” usually means the pool is too small for the traffic, or queries hold connections too long. Look at slow queries before you grow the pool.
04 When the pools outgrow the database
The database has its own limit: max_connections, 100 by default in PostgreSQL. Every app server holds its whole pool open, busy or not, so the connections in use are servers times pool size. Add servers during a spike and you can hit the limit. The next server that tries to connect is refused with FATAL: sorry, too many clients already, and its requests fail, while the database itself is barely busy.
- DB connections
- 30 / 40
- Refused
- 0
- Failed
- 0
- Served
- 0
Click a waiting request (yellow square) or a busy connection (orange) to follow that request.
- 3 app servers × 10 = 30 of 40 database connections.
This is the failure in the building-blocks system when the app tier scales out. Autoscaling app servers without planning database connections turns a traffic spike into an outage.
05 A pooler in front
A connection pooler such as PgBouncer sits between the app servers and the database. It accepts thousands of cheap client connections and shares a small number of real database connections between them, lending one to each transaction and taking it back at the end.
Fewer connections is not just allowed, it is faster. A database with four cores can only run about four queries at a time. Forty active queries share those cores and get in each other’s way, so each one runs slower and the whole burst finishes later.
- DB connections
- 40 / 40
- Refused
- 40
- Failed
- 0
- Response time
- 0 ms
Click a waiting request (yellow square) or a busy connection (orange) to follow that request.
- Server 5: FATAL: sorry, too many clients already (40 of 40 connections in use).
A good starting size for the database side is a small multiple of its CPU cores. Watch for features that break in transaction pooling mode, such as session settings and some prepared statements.
06 Transactions, locks and deadlocks
A transaction groups statements so they all happen or none do. Moving money from account A to B is two updates in one transaction: if the second fails, the first is rolled back.
While a transaction updates a row it holds a lock on that row until it commits. A second transaction that wants the same row waits. That is normal and usually short.
A deadlock is when two transactions each hold a row the other wants. T1 holds A and waits for B; T2 holds B and waits for A. Neither can ever move. Databases check for this cycle after a short wait (one second by default in PostgreSQL), roll one transaction back with an error, and let the other finish. The application must retry the one that was rolled back.
- Committed
- 0
- Longest wait
- 0.0s
- Deadlocks
- 0
Click a transaction to follow what it did.
Keep transactions short, touch rows in a consistent order (for example by id), and retry on deadlock errors. A deadlock is a bug to reduce, not a crash.
07 Lost updates and isolation
Locks only protect what you ask them to. A common pattern reads a value, changes it in the app and writes it back. If two clients do this at once, both read 100, both write 110, and one +10 disappears without any error. That is a lost update.
The database’s isolation level decides how much one transaction sees of others running at the same time. PostgreSQL’s default, Read Committed, allows this lost update. The fixes:
- Atomic update. Do the arithmetic in the database:
UPDATE accounts SET balance = balance + 10. The row lock covers the read and the write. - SELECT ... FOR UPDATE. Lock the row when you read it, so the other client waits until you commit and then reads the new value.
- A stricter isolation level. Under Repeatable Read or Serializable, PostgreSQL refuses the second write with a serialization error, and the app retries from the read.
- Times +10
- 0
- Balance
- 100
- Lost updates
- 0
- Retries
- 0
- Lock waits
- 0
Click a client to follow what it read and wrote.
Whenever code reads a value and writes back something computed from it, ask what happens if two requests do it at once. The flash sale system guards its stock count exactly this way.
08 Replication and reading your own writes
One database server can only answer so many reads, and it is a single point of failure. Replication keeps copies. Every change is first written to the primary’s write-ahead log (WAL), and the primary streams that log to replicas, which replay it. Reads can then go to any replica.
Streaming takes time, usually milliseconds, sometimes seconds under heavy load. That delay is replication lag. A user who saves something and reads it straight back from a replica may not see their own change.
- Saves
- 0
- Replica lag
- 0.0s
- Stale reads
- 0
- Fresh reads
- 0
Click any numbered chip to follow that one save.
Send a user’s reads to the primary for a few seconds after they write, or remember the log position of their write and only read from a replica that has reached it.
09 Failover: what the lag window costs
When the primary dies, a replica can be promoted to take its place. Detecting the failure and promoting takes a few seconds, and writes fail during that gap.
The bigger question is what the new primary is missing. With asynchronous replication, the default, the primary confirms a commit as soon as it has the write, before any replica does. Writes still in the lag window when it dies were confirmed to users and are now gone. With synchronous replication the primary waits for a replica to confirm before it answers, so nothing confirmed is lost, but every commit takes a network round trip longer.
- Saves
- 0
- Commit wait
- 0 ms
- Lost writes
- 0
- Failed writes
- 0
Click any numbered chip to follow that one save.
Decide per database what you can afford to lose. Payments usually pay for synchronous commit; a feed of likes usually does not.
10 Scaling up or out
When one database cannot keep up, there are two directions. Vertical scaling moves to a bigger machine: more cores, more memory, faster disks. Nothing in the app changes, which is why it is almost always the first step. It stops at the biggest machine you can buy, and that machine is still one machine.
Horizontal scaling splits the data across several databases, called shards, by a key such as customer id. A query that includes the key goes to one shard, and each shard adds capacity. A query without the key has to ask every shard and wait for all of them, so it costs the same work on every machine.
- Done per second
- 0.0
- Capacity
- 10/s
- Waiting
- 0
- Avg latency
- 0 ms
Click a waiting dot or a busy core to follow that query.
- 20 queries a second, each needing 400 ms of one core. Capacity about 10 a second.
Scale up first, add read replicas for read-heavy load, and shard only when writes or data size outgrow one machine. Choosing the shard key is the hard part: see the sharding lesson.
11 Choosing a database
Everything above applies to every relational database; each makes its own choices about it. A rough map:
| Database | Shape | Connections and locking | Replication | Good for |
|---|---|---|---|---|
| PostgreSQL | Server; B-tree indexes plus GIN, GiST, BRIN; many extensions | One process per connection, so a pooler is common; MVCC, Read Committed by default | WAL streaming, asynchronous by default, synchronous per setting | A strong default for most apps |
| MySQL (InnoDB) | Server; table stored in primary key order, secondary indexes point to the key | A thread per connection; MVCC, Repeatable Read by default | Binary log, asynchronous or semi-synchronous; group replication | Web apps, large existing ecosystems |
| SQLite | A library and one file inside your process | No network or pool; one writer at a time, readers alongside in WAL mode | None built in | Apps, devices, tests, small sites |
| Cloudflare D1 | Managed SQLite on Cloudflare’s network | Queried over HTTP or a Worker binding; one primary per database | Read replicas with a sessions API for reading your writes | Workers apps, many small databases |
| Managed services (Amazon RDS and Aurora, Google Cloud SQL, Neon, Supabase, PlanetScale) | PostgreSQL or MySQL run for you | Same engines; many include a pooler | Replicas, backups and failover handled for you | Teams that would rather not run databases |
Managed services take away backups, patching and failover, not indexes, transactions or connection limits. Check the current docs before you choose: defaults, limits and features change often.
12 Check yourself
Looking up a user by email takes 900 ms on a table of 5 million rows. EXPLAIN shows "Seq Scan on users". What is the usual fix?
During a sale you autoscale from 10 to 30 app servers. Each keeps a pool of 20 connections. max_connections is 300. What happens?
Two requests read stock = 5 for the same product, each subtract one in the app, and each write 4. What went wrong?
A user saves their profile, the page reloads and shows the old name. Reads go to replicas. Why?
Replication is asynchronous. The primary crashes and a replica is promoted. What can happen to writes that were already confirmed to users?