How systems work

Databases.

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.

Ana's browserthe userApp serverruns your codeconnection poolPrimary databasetakes every writeIndex on idB-tree1–1M1–500k500k+1–3940–79……users table1M rows40cy@x.io41bo@x.io42ana@old.io43di@x.io44ed@x.ioWrite-ahead logevery change, in order#55#56Replicaa read-only copyapplied up to #5642 ana@old.io

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.

WaitingnoneRunningWaiting for a queryusers · 100,000 rows · each block ≈ 1,563Examined 0 of 100,000 rowsrootNo index on email
Waiting
0
Rows examined
0
Lookup time
0 ms

Click any query chip to follow that one query.

Lookups by email on a table of users. Each block in the grid is a slice of the table; lit blocks have been read.
Rows in the table
    Try this. Watch the queue grow: each scan takes longer than the gap between queries. Turn on the index. Rows examined drops to 1, the B-tree path lights up and the queue drains. Then switch to 1,000,000 rows: the index still reads four pages. Turn the index off at that size and each lookup takes ten seconds.

    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.

    WaitingnoneRunningWaiting for a queryusers table+1 rowindex on email+1 entry
    Waiting
    0
    Writes per insert
    2
    Insert time
    0 ms

    Click any query chip to follow that one query.

    Inserts into the users table. Each bar is one structure the insert has to write.
      Try this. Add other indexes one at a time and watch each insert get longer. At five, an insert writes seven structures and the database can no longer keep up with one insert a second: the queue starts to grow.

      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.

      App serversDatabaseApp 1pool of 3no one waitingDatabasemax_connections 400 running on 8 coresidle
      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.

      One app server with a pool of three. Orange dots are connections in use; yellow squares are requests waiting for one.
      1. 1 app server × 3 = 3 of 40 database connections.
      Try this. Three connections each serve two requests a second, but eight arrive. Requests wait, the wait reaches two seconds and they start failing. Raise the pool size to 6 and the waiting line disappears.

      “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.

      App serversDatabaseApp 1pool of 10no one waitingApp 2pool of 10no one waitingApp 3pool of 10no one waitingDatabasemax_connections 400 running on 16 coresidle
      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.

      App servers with pools of ten, against a database that allows forty connections. Each cell on the right is a connection slot; dashed ones are free.
      1. 3 app servers × 10 = 30 of 40 database connections.
      Try this. Go from three servers to four: forty of forty slots are taken. Add a fifth. Its connections are refused (red crosses) and every request routed to it fails, even though most connections sit idle.

      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.

      App serversDatabaseApp 1pool of 10no one waitingApp 2pool of 10no one waitingApp 3pool of 10no one waitingApp 4pool of 10no one waitingApp 5pool of 10no connectionsApp 6pool of 10no connectionsApp 7pool of 10no connectionsApp 8pool of 10no connectionsDatabasemax_connections 400 running on 4 coresidle
      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.

      Eight app servers with pools of ten: eighty connections wanted, forty allowed. The bar under the database shows how many cores are busy; it turns red when queries crowd each other.
      1. Server 5: FATAL: sorry, too many clients already (40 of 40 connections in use).
      Try this. Turn the pooler on. All eighty app connections now succeed, and the database holds only eight. Send a burst of 40 and note the response time. Then set the pooler’s connections to 40 and send another burst: every query runs at once, the bar turns red, each query runs several times slower and the response time climbs.

      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.

      Transaction 1Transaction 2RowsRow AunlockedRow BunlockedT1transactionBEGINUPDATE row AUPDATE row BCOMMITIdle, next in 0.0sT2transactionBEGINUPDATE row AUPDATE row BCOMMITIdle, next in 0.3s
      Committed
      0
      Longest wait
      0.0s
      Deadlocks
      0

      Click a transaction to follow what it did.

      Two transactions that both update rows A and B. Solid lines are locks held; dashed red lines are waits.
        Try this. With the same order, T2 waits for T1 to commit, then runs. Untick the box so T2 updates B first. Now each holds one row and waits for the other: two dashed lines, a cycle. After a second, T1 is rolled back, T2 finishes, and T1 runs again.

        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.
        App client AApp client BThe rowbalance100should be 100AIdleBIdle
        Times +10
        0
        Balance
        100
        Lost updates
        0
        Retries
        0
        Lock waits
        0

        Click a client to follow what it read and wrote.

        Two clients each add 10 to one balance every few seconds, overlapping a little. Chips carry the value read or written.
        How each client adds 10
          Try this. With read, then write, watch both clients read the same balance and the “should be” number pull away from the real one. Switch to each fix in turn. Atomic update never loses one. FOR UPDATE makes B wait for the lock. Repeatable read lets B fail and retry.

          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.

          YouYousaving…reading back…Primarynode 0empty so fartakes the writesReplicanode 1empty so farin syncReplicanode 2empty so farin sync
          Saves
          0
          Replica lag
          0.0s
          Stale reads
          0
          Fresh reads
          0

          Click any numbered chip to follow that one save.

          You save a change, then read it back 0.2 seconds later from a replica. Purple chips are log records on their way to each replica.
            Try this. With 600 ms of lag, almost every read comes back stale. Drag the lag down to 100 ms and the reads turn fresh. Put the lag back up and tick “Read your own writes from the primary”: fresh every time, and other users’ reads can still use the replicas.

            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.

            YouYousaving…writing onlyPrimarynode 0empty so fartakes the writesReplicanode 1empty so farin syncReplicanode 2empty so farin syncConfirmed writes lost: none yet
            Saves
            0
            Commit wait
            0 ms
            Lost writes
            0
            Failed writes
            0

            Click any numbered chip to follow that one save.

            Three writes a second into a primary with two replicas. Crash the primary and see which confirmed writes survive.
              Try this. Crash the primary. Writes fail for two seconds, then the most up-to-date replica is promoted, and the writes it never received are listed as lost. Press Reset, tick synchronous replication, and crash it again: nothing confirmed is lost, but commit wait has gone from zero to most of a second.

              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.

              One database machine20 queries/s in4 cores0 waiting
              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.

              Each square is a core; each dot is a query waiting. Dark ones have no shard key and land on every shard.
              Scale by
              Cores in the machine
              1. 20 queries a second, each needing 400 ms of one core. Capacity about 10 a second.
              Try this. Twenty queries a second swamp four cores. Eight cores just keep pace; sixteen clear the line. Switch to shards: four shards of four cores keep up too. Now raise the share of queries without the shard key. Every one of those occupies a core on every shard, and throughput falls back towards what one shard can do.

              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:

              DatabaseShapeConnections and lockingReplicationGood for
              PostgreSQLServer; B-tree indexes plus GIN, GiST, BRIN; many extensionsOne process per connection, so a pooler is common; MVCC, Read Committed by defaultWAL streaming, asynchronous by default, synchronous per settingA strong default for most apps
              MySQL (InnoDB)Server; table stored in primary key order, secondary indexes point to the keyA thread per connection; MVCC, Repeatable Read by defaultBinary log, asynchronous or semi-synchronous; group replicationWeb apps, large existing ecosystems
              SQLiteA library and one file inside your processNo network or pool; one writer at a time, readers alongside in WAL modeNone built inApps, devices, tests, small sites
              Cloudflare D1Managed SQLite on Cloudflare’s networkQueried over HTTP or a Worker binding; one primary per databaseRead replicas with a sessions API for reading your writesWorkers apps, many small databases
              Managed services (Amazon RDS and Aurora, Google Cloud SQL, Neon, Supabase, PlanetScale)PostgreSQL or MySQL run for youSame engines; many include a poolerReplicas, backups and failover handled for youTeams 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

              1. 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?

              2. During a sale you autoscale from 10 to 30 app servers. Each keeps a pool of 20 connections. max_connections is 300. What happens?

              3. Two requests read stock = 5 for the same product, each subtract one in the app, and each write 4. What went wrong?

              4. A user saves their profile, the page reloads and shows the old name. Reads go to replicas. Why?

              5. Replication is asynchronous. The primary crashes and a replica is promoted. What can happen to writes that were already confirmed to users?

              Next partRate limiters