Skip to content

Relational databases

A relational database (RDBMS) stores data as tables of typed rows, enforces rules about that data, and lets many clients change it concurrently through transactions. PostgreSQL, MySQL, SQL Server and Oracle still hold the system of record for most companies. To design around one, you need to know three things: what its guarantees actually promise, where they quietly stop, and how far a single node will take you.

Data lives in tables (relations) made of rows (tuples) with typed columns. A primary key identifies each row. Foreign keys link rows across tables. Normalisation means each fact is stored once: a customer’s address lives in customers, and every order points to it. You do not copy the address into each order.

Two properties make the model durable after 50 years:

  • Declarative queries. SQL says what you want. The optimiser picks how: which index, which join algorithm, which order. When the data grows, the plan can change without touching application code.
  • Constraints in one place. NOT NULL, UNIQUE, CHECK and foreign keys are enforced by the database for every client. An application bug cannot slip past them.

The line between relational and document stores has blurred. PostgreSQL’s jsonb columns can be indexed, and many document databases now offer multi-document transactions. The deciding questions are about access patterns and guarantees, not labels. See SQL or NoSQL.

PropertyWhat it guaranteesHow engines implement itCommon misreading
AtomicityAll writes in a transaction take effect, or none do: on crash, abort or a constraint errorWrite-ahead log (WAL) plus undo informationIt says nothing about concurrent access
ConsistencyEach transaction moves the data from one valid state to anotherConstraints, triggers, and your codeNot the “C” in CAP. That one means linearizability.
IsolationConcurrent transactions do not see each other’s partial workLocks, MVCC snapshots, conflict detectionRarely full serializability by default
DurabilityOnce COMMIT returns, the change survives a process or OS crashWAL flushed to disk before the acknowledgementOne disk survives a crash, not machine loss. That needs replication.

Two practical notes. First, the “C” belongs mostly to the application: the database guarantees only the rules you declared. Second, durability is often traded for latency on purpose. Examples are synchronous_commit = off in PostgreSQL or asynchronous replicas that may lose the last few transactions on failover.

  • Keep them short. A transaction holds locks and pins old row versions until it ends. Never wait on a user, an HTTP call or a message queue inside one.
  • Prefer atomic statements to read-modify-write. UPDATE accounts SET balance = balance - 10 WHERE id = 1 AND balance >= 10 cannot lose an update. Reading the balance into the application, subtracting there and writing it back can.
  • Lock explicitly when you must. SELECT ... FOR UPDATE locks the rows you read, so a concurrent writer waits.
  • Use optimistic concurrency for long edits. Add a version column and write UPDATE ... SET version = version + 1 WHERE id = ? AND version = ?. If zero rows changed, someone else won, so reload and retry.
  • Retry on serialisation failures and deadlocks. At stricter levels the database aborts a transaction instead of corrupting data (SQLSTATE 40001). Make transactions safe to re-run.

Isolation levels are defined by the anomalies they allow:

  • Dirty read: you see another transaction’s uncommitted write, which may later roll back.
  • Non-repeatable read: you read a row twice and get different values, because another transaction committed in between.
  • Phantom: you re-run a range query (WHERE room = 7 AND day = '2026-10-08') and rows have appeared or vanished.
  • Lost update: two transactions read the same value, both modify it, and the second write silently overwrites the first.
  • Write skew: two transactions read the same data, each decides based on it, and they write different rows. Each write is fine alone, but together they break an invariant.

The textbook matrix below follows the 1995 Berenson et al. critique, which added lost update, write skew and snapshot isolation to the ANSI definitions:

LevelDirty readNon-repeatable readPhantomLost updateWrite skew
Read uncommittedPossiblePossiblePossiblePossiblePossible
Read committedPreventedPossiblePossiblePossiblePossible
Repeatable read (lock-based)PreventedPreventedPossiblePreventedPossible via phantoms
Snapshot isolationPreventedPreventedPrevented in readsPrevented¹Possible
SerializablePreventedPreventedPreventedPreventedPrevented

¹ Only if the engine aborts the second of two concurrent writers to the same row (“first committer wins”). PostgreSQL does this. MySQL’s repeatable read does not.

The classic example is a hospital rule: at least one doctor must be on call. Alice and Bob are both on call, and both ask to go off duty at the same moment.

sequenceDiagram
  participant A as Transaction A (Alice)
  participant DB as Database
  participant B as Transaction B (Bob)
  A->>DB: count doctors on call
  DB-->>A: 2
  B->>DB: count doctors on call
  DB-->>B: 2
  A->>DB: set Alice off call
  B->>DB: set Bob off call
  A->>DB: COMMIT
  B->>DB: COMMIT
  Note over A,B: No row was written twice, yet nobody is on call

We ran exactly this against PostgreSQL 16. Under read committed and repeatable read, both transactions commit and zero doctors remain on call. Under serializable, the second commit fails with could not serialize access due to read/write dependencies among transactions. The application retries, sees one doctor on call, and refuses the request. Without serializable isolation, the fix is to lock the rows you based the decision on (SELECT ... FOR UPDATE) or to turn the invariant into a constraint.

The names of the levels are shared, but the behaviour is not:

EngineDefault levelWhat the levels really mean
PostgreSQLRead committedRead uncommitted behaves as read committed. Repeatable read is snapshot isolation: a concurrent update to the same row aborts with could not serialize access due to concurrent update. Serializable is Serializable Snapshot Isolation (SSI).
MySQL (InnoDB)Repeatable readPlain SELECTs read a snapshot. UPDATE, DELETE and locking reads see the latest committed row and take next-key locks. Lost updates in read-modify-write code are not detected.
OracleRead committedIts “serializable” is snapshot isolation, so write skew is possible.
SQL ServerRead committed (locking)Row-versioned read committed (RCSI) is the default on Azure SQL Database. A separate SNAPSHOT level exists.
CockroachDB, SpannerSerializableWeaker levels are opt-in (read committed in CockroachDB, repeatable read in Spanner).
Aurora DSQLRepeatable read (fixed)Snapshot isolation with optimistic concurrency: conflicts surface at commit as SQLSTATE 40001, so clients must retry.

Multi-version concurrency control keeps several versions of a row. A write creates a new version stamped with its transaction ID. A reader picks the newest version that was committed before its snapshot was taken. Readers therefore never block writers, and writers never block readers. Two writers to the same row still conflict.

Engines differ in where the old versions live:

  • PostgreSQL writes each new version as a new tuple in the table itself. The old tuple stays until VACUUM removes it once no snapshot can see it.
  • InnoDB updates the row in place and keeps the previous version in an undo log. A background purge discards undo records nobody needs.

The operational catch is the same in both. A transaction left open for hours pins every version created since it started. In PostgreSQL the tables bloat. In InnoDB the undo history grows. Monitor the age of the oldest open transaction and kill forgotten sessions.

flowchart TB
  subgraph lsm["LSM-tree engine"]
    direction TB
    w2["Write"] --> wal2["Append to WAL"]
    wal2 --> mem["In-memory sorted table"]
    mem -- "flush when full" --> sst[("Immutable sorted files")]
    sst -- "background compaction" --> sst
  end
  subgraph btree["B-tree engine"]
    direction TB
    w1["Write"] --> wal1["Append to WAL"]
    wal1 --> page["Modify page in place"]
    page --> tree[("Sorted tree of<br/>fixed-size pages")]
  end
B-treeLSM-tree
Write pathFind the page, change it, log the changeAppend to log and memory buffer, flush sorted files, merge them later
Point readsOne descent of a shallow tree: predictableMay check the buffer plus several files. Bloom filters skip most of them.
Write amplificationA small change rewrites a whole pageCompaction rewrites data several times, but sequentially
SpaceFree space inside pagesObsolete versions linger until compaction. Compresses well.
Typical fitRead-heavy OLTP, range scansWrite-heavy ingestion, large datasets on SSDs
ExamplesPostgreSQL, InnoDB, SQL Server, OracleRocksDB, Cassandra, CockroachDB (Pebble), YugabyteDB (DocDB, built on RocksDB)

You rarely choose a storage engine directly. You choose a database, and the engine decides which workloads are cheap. A system that ingests millions of small events per second is a natural LSM workload. A system that serves complex joins over a stable dataset is a natural B-tree workload.

When a relational database is the right choice

Section titled “When a relational database is the right choice”

Reach for an RDBMS first when:

  • The data is a system of record: money, orders, inventory, identity, permissions.
  • Invariants span rows or tables: “a seat is sold once”, “debits equal credits”. Transactions and constraints enforce them in one place.
  • You need ad-hoc queries and joins, and you do not know every access pattern up front.
  • The working set fits one primary. Most do. A single modern server with tens of cores, hundreds of gigabytes of RAM and NVMe storage handles a large share of real products, and managed services handle backups, failover and patching.

Look elsewhere, or alongside, for very high-volume key-value access with simple queries (NoSQL), large binary objects (object storage), heavy analytics over billions of rows (a columnar warehouse), or deep graph traversals.

flowchart TD
  s1["1. Tune queries and indexes"] --> s2["2. Scale up the server"]
  s2 --> s3["3. Pool connections, cache hot reads"]
  s3 --> s4["4. Add read replicas"]
  s4 --> s5["5. Federate or partition tables"]
  s5 --> s6["6. Shard, or adopt distributed SQL"]

Each step costs more complexity than the one before it, so climb only when measurements say the current step is exhausted:

  • Query and schema tuning, denormalisation: often a 10× to 1000× win for one query, at almost no architectural cost. See Denormalisation and SQL tuning.
  • Caching: takes repeated reads off the database. See Caching layers.
  • Read replicas: scale reads and add failover targets, but bring replication lag. See Replication.
  • Federation and sharding: scale writes and storage beyond one node, at the cost of cross-shard queries and transactions. See Partitioning and sharding.
Isolation levelCostGood for
Read committedCheapest. Few aborts.Most CRUD work, with atomic UPDATEs and explicit locks where invariants matter
Repeatable read / snapshotConsistent view for the whole transaction. PostgreSQL may abort concurrent writers.Reports, exports, multi-step reads that must agree with each other
SerializableMore aborts and retries, some tracking overheadInvariants across rows (bookings, balances, quotas) when you would rather not reason about locks

Based on The System Design Primer by Donne Martin (CC BY 4.0). Restructured, rewritten and updated; site content is licensed under CC BY 4.0.