OverviewsDatabases

Databases overview

Contents
  1. Start from the access patterns
  2. Model so each fact lives in one place
  3. Indexes decide which queries are cheap
  4. Connections are scarce
  5. Isolation levels are a contract about anomalies
  6. MVCC keeps readers and writers apart
  7. The write-ahead log is what “committed” means
  8. B-trees and LSM-trees trade reads against writes
  9. Replication is a consistency decision
  10. Partitioning and sharding
  11. Backups exist to be restored
  12. Schema changes in expand and contract steps
  13. What to keep on the dashboard
  14. Sources

A database is a program that keeps data correct while many clients read and change it at once, and keeps it after the power goes out. Almost every hard problem in the field is one of those two promises meeting real hardware: concurrency, durability, or what happens when one machine isn’t enough.

This page covers the twelve things I watch when I dig into a database or a schema someone hands me. The examples use PostgreSQL because its documentation is precise about each mechanism, and I point out where MySQL or other engines differ. Each section says what the concept is, what to measure, and why it is worth tracking. The prompting guide for this topic turns the same ideas into named terms and prompt lines.

Start from the access patterns

Before tables or engines, write down every read and write the application will perform: what it filters on, what it sorts by, how often it runs and how fast it must be. The AWS DynamoDB guide puts it bluntly and says you shouldn’t start designing a schema until you know the questions it has to answer. The same holds for a relational database, even though it lets you ask new questions later.

Each kind of access pattern points at a different data model, so the list of reads comes before the choice of database.

Track the list itself, with numbers next to each pattern. Most “we picked the wrong database” stories turn out to be a pattern nobody wrote down, like the report that scans a year of orders or the lookup by email that has no index.

Model so each fact lives in one place

Codd’s 1970 paper defined the relational model, and the normal forms that followed are rules for storing each fact once. William Kent’s summary is the one to remember: every non-key field gives a fact about “the key, the whole key, and nothing but the key.” When a customer’s address sits on every order row, changing it means finding every copy, and missing one is an update anomaly.

The address repeated on every order moves to a customers table, and orders point at it through a foreign key.

What I track here is where the schema duplicates data and whether each duplicate is on purpose. Denormalizing a total onto an order for speed is fine when someone wrote down why and something keeps it correct. Constraints are the other half: PostgreSQL’s docs recommend NOT NULL on most columns, and foreign keys, CHECK and UNIQUE constraints catch bad data that application code misses.

Indexes decide which queries are cheap

A B-tree index keeps keys sorted in a shallow tree of pages, so a lookup reads a few pages instead of the whole table. Markus Winand writes on Use the Index, Luke that real indexes with millions of rows have a depth of four or five. The leaves are linked to each other, which is why the same index serves ranges and ORDER BY as well as equality.

Finding one email walks from the root to a leaf in three page reads, and the leaves link sideways for range scans.

The thing to track is the query plan, not the list of indexes. PostgreSQL’s EXPLAIN (ANALYZE, BUFFERS) shows each step with estimated and actual row counts, and its docs treat a large gap between the two as the first sign the planner is working from bad statistics. Column order matters too: an index on (customer_id, created_at) serves a filter on customer, or customer and date, but not date alone. Every extra index also costs time on each insert and update, so an index that no query uses is pure cost.

Connections are scarce

PostgreSQL starts one operating system process per connection, and max_connections is typically 100. An application with hundreds of workers that each hold a connection runs out quickly, and each idle connection still uses memory on the server.

A pooler in transaction mode lets hundreds of app workers share about twenty server connections.

I track connections in use against the limit, and how many sit idle inside an open transaction. PgBouncer’s transaction mode hands a server connection to a client only for the length of one transaction, which is how a small pool serves a large app. The PgBouncer docs list what breaks in that mode, such as session-level SET and advisory locks, so the application has to be written for it.

Isolation levels are a contract about anomalies

An isolation level says which surprises one transaction can see from others running at the same time. PostgreSQL defaults to Read Committed, where each statement sees data committed before it started. MySQL’s InnoDB defaults to Repeatable Read, and Jepsen’s 2023 analysis of MySQL 8.0.34 found its Repeatable Read allows anomalies that the name suggests it prevents. Berenson and colleagues’ 1995 paper “A Critique of ANSI SQL Isolation Levels” named the anomalies that matter, including lost update and write skew.

Two transactions each check that someone else is on call, both go off call, and the rule breaks without either one doing anything wrong alone.

Track two things per transaction: which level it runs at, and what it does when the database aborts it. PostgreSQL’s Serializable level, built on the serializable snapshot isolation work by Ports and Grittner, catches write skew by failing one transaction with SQLSTATE 40001. That only helps if the code retries the whole transaction, including the reads that chose what to write.

MVCC keeps readers and writers apart

PostgreSQL’s docs state that under MVCC “reading never blocks writing and writing never blocks reading.” An UPDATE doesn’t overwrite a row. It writes a new version and marks the old one with the transaction that replaced it, so a reader with an older snapshot still sees the old value.

An update writes a new row version, older snapshots keep reading the old one, and VACUUM reclaims it once no snapshot needs it.

The cost is cleanup. Old versions become dead tuples that autovacuum has to clear, and a transaction left open for an hour stops it from clearing anything newer than that transaction’s snapshot. I track dead tuples per table, the age of the oldest open transaction, and transaction ID age. PostgreSQL’s transaction IDs are 32 bits, and its routine vacuuming docs explain that every table must be frozen before about two billion transactions pass, or the server stops accepting writes to protect the data.

The write-ahead log is what “committed” means

When COMMIT returns, PostgreSQL has not written the changed table pages to disk. It has appended a record of the change to the write-ahead log and flushed that log. The data files catch up later at a checkpoint, and after a crash the server replays the log from the last checkpoint.

A commit is durable once its log record is flushed, data pages reach disk later at a checkpoint, and a crash is repaired by replaying the log.

Track the settings that weaken this promise and who changed them. PostgreSQL’s docs warn that fsync = off can lead to unrecoverable corruption after a crash, while synchronous_commit = off only risks losing the last few commits. In MySQL the matching setting is innodb_flush_log_at_trx_commit, where the default of 1 flushes the log at every commit. The WAL matters beyond crashes too, because replication, point-in-time recovery and change data capture all read it.

B-trees and LSM-trees trade reads against writes

Most relational engines store data in B-tree pages and update them in place. LSM-trees, described by O’Neil and colleagues in 1996 and used by RocksDB and Cassandra, buffer writes in memory, flush them as sorted immutable files, and merge those files in the background.

A B-tree rewrites pages in place, while an LSM-tree appends sorted files and pays later in compaction.

The RocksDB tuning guide frames the choice as three costs: write amplification, read amplification and space amplification, and no design wins all three. I track which one the workload can afford. An LSM engine takes heavy inserts cheaply, but a point read may check several files, which is what its bloom filters are for, and deletes leave tombstones that slow reads until compaction removes them.

Replication is a consistency decision

PostgreSQL streaming replication is asynchronous by default. The primary commits without waiting, and a replica applies the change a moment later. Reading from replicas spreads load, but it means a user can write something and then not see it.

A user posts to the primary, reloads from a replica that is 300 ms behind, and their comment is missing.

Track replication lag as a number with an alert, and decide per read which consistency the user needs. Jepsen’s consistency model map names the options precisely: read-your-writes, monotonic reads, linearizable and others. Asynchronous replication also decides what a failover loses, and Gilbert and Lynch’s proof of the CAP theorem shows that during a network partition a system must choose between staying available and staying linearizable. Daniel Abadi’s PACELC adds that even without a partition, stronger consistency costs latency.

Partitioning and sharding

Partitioning splits one table into pieces on one server. Sharding splits data across servers by a shard key. PostgreSQL’s docs suggest partitioning when a table grows larger than the server’s memory, and warn never to assume more partitions are better than fewer.

Hashing the shard key spreads rows across shards, but one very busy key still lands on one shard.

The shard key is the decision to track, because it is close to permanent. A good key keeps each request on one shard and spreads load evenly. The DynamoDB docs give a concrete limit: one partition handles up to 3,000 reads and 1,000 writes per second, so a single popular key caps throughput no matter how many partitions exist. Queries that don’t include the key have to ask every shard.

Backups exist to be restored

A replica is not a backup, because it copies a bad DELETE within seconds. Point-in-time recovery in PostgreSQL restores a base backup and replays archived WAL up to a chosen moment, such as one minute before the mistake. PostgreSQL’s docs note that pg_dump can’t do this, since it produces a snapshot with no log to replay.

Restore Sunday's base backup, replay archived WAL up to 14:02, and the table dropped at 14:03 comes back.

Track the date of the last restore you actually tested, and how long it took. The AWS disaster recovery whitepaper defines the two targets: recovery point objective is how much data you can lose, and recovery time objective is how long you can be down. Archiving that silently fails, or a restore nobody has timed, turns both numbers into guesses.

Schema changes in expand and contract steps

Most forms of ALTER TABLE in PostgreSQL take an ACCESS EXCLUSIVE lock, which blocks even reads. If that statement waits behind a long query, every query that arrives after it queues behind the ALTER, so a quick change can still stall the application. Setting lock_timeout makes the DDL give up and retry instead.

Four separate deploys: add the new shape, migrate data while writing both, switch reads, then drop the old shape.

Danilo Sato’s parallel change article on martinfowler.com describes the expand and contract pattern. I track whether each migration step can run while the old and new application versions both serve traffic, and whether it can roll back. PostgreSQL has tools for the risky parts: CREATE INDEX CONCURRENTLY builds an index without blocking writes, and a constraint added as NOT VALID can be checked later with VALIDATE CONSTRAINT.

What to keep on the dashboard

These are the numbers I check first on a database I’m responsible for.

SignalWhy it matters
Top statements by total time, from pg_stat_statementsA few query shapes usually cause most of the load, and fixing them beats tuning settings.
Connections in use against max_connectionsRunning out looks like an outage to every client at once.
Replication lagIt decides what readers see and what a failover loses.
Dead tuples and autovacuum runs per tableFalling behind bloats tables and slows every scan.
Transaction ID ageLeft alone, it forces the server to stop accepting writes.
Oldest open transactionOne forgotten transaction blocks cleanup for the whole database.
WAL directory size and replication slot retentionA stuck archive or an abandoned slot fills the disk.
Lock waits and deadlocksThey show where concurrent writes collide.
Date and duration of the last tested restoreIt is the only evidence that the backups work.

Sources