Skip to content

Lesson 6 of 38Building blocks

Databases

Choose between SQL and the NoSQL families, explain ACID and isolation, and know what indexes cost and buy you.

18 min read0/4 questions

The database is the one box in your design you cannot easily throw away and replace. Servers are stateless and caches can be rebuilt, but the database holds the truth, and migrating terabytes off the wrong one takes months. Interviewers almost always ask "which database, and why?", and the answer they respect is specific: the access patterns, the consistency needs, and the scale.

Relational databases

A relational (SQL) database stores data in tables with a fixed schema: columns with types and constraints. Rows reference each other by keys, and you combine them with joins. You ask questions in SQL, and the database figures out how to answer them. PostgreSQL, MySQL, SQL Server, and SQLite are relational.

schema.sql
CREATE TABLE users (
  id         BIGSERIAL PRIMARY KEY,
  email      TEXT UNIQUE NOT NULL,
  created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
 
CREATE TABLE orders (
  id       BIGSERIAL PRIMARY KEY,
  user_id  BIGINT NOT NULL REFERENCES users(id),
  total    NUMERIC(10, 2) NOT NULL,
  status   TEXT NOT NULL
);
 
SELECT u.email, sum(o.total)
FROM users u JOIN orders o ON o.user_id = u.id
WHERE o.status = 'paid'
GROUP BY u.email;

Their superpower is flexibility: you can ask questions you did not plan for when you designed the schema, and the database enforces rules (unique emails, every order has a real user) so bad data cannot get in.

The NoSQL families

NoSQL is an umbrella for databases that give up some of that flexibility, usually joins and multi-row transactions, in exchange for easier horizontal scaling or a data model that fits a specific job.

TypeData modelExamplesGreat forWeak at
RelationalTables, rows, joinsPostgreSQL, MySQLMost apps: users, orders, paymentsVery high write volume across many machines
DocumentJSON-like documentsMongoDB, FirestoreNested, flexible records read as a whole (a product with variants)Joins across collections
Key-valueKey → opaque valueRedis, DynamoDBLookups by one key: sessions, carts, feature flagsQuerying by anything except the key
Wide-columnPartition key → sorted rowsCassandra, ScyllaDB, BigtableHuge write volume, time series, chat historyAd-hoc queries, joins
GraphNodes and edgesNeo4j, Amazon NeptuneDeep relationships: "friends of friends who like X"Simple tabular workloads
SearchInverted indexElasticsearch, OpenSearchFull-text search, filters, rankingBeing the source of truth

The deciding question is your access patterns: what queries run, how often, and with what keys. Wide-column and key-value stores make you design tables around queries up front; get it wrong and some queries become impossible without a full scan.

Real systems use several stores side by side, each for what it is good at. Step through where each request goes.

One app, several databases
ClientClientAPI serviceAPI servicePostgreSQL: users, ordersPostgreSQLusers, ordersRedis: sessions, cartsRedissessions, cartsOpenSearch: product searchOpenSearchproduct searchCassandra: activity eventsCassandraactivity eventsHTTPSSQLGET/SETqueryappendsync (CDC)

GET /cart: look up the cart by session id in Redis. One key, about 1 ms.

1/5
Match the pairs0/5 matched

Match each workload to a good first choice.

Choose an item, then its match on the other side.

ACID transactions

A transaction is a group of operations that succeed or fail together. Relational databases (and some NoSQL ones, within limits) guarantee ACID:

  • Atomicity: all or nothing. If the transfer crashes halfway, neither account changes.
  • Consistency: the database moves from one valid state to another; constraints like balance >= 0 and foreign keys always hold.
  • Isolation: concurrent transactions do not see each other's half-finished work.
  • Durability: once COMMIT returns, the data survives a crash (it is in the write-ahead log on disk).
A money transfer as one transaction
AppPostgresBEGINUPDATE accounts SET balance = balance - 100 WHERE id = 'ada'UPDATE accounts SET balance = balance + 100 WHERE id = 'sam'COMMITCOMMIT OK (written to WAL)

BEGIN

1/5

Isolation levels in plain words

Full isolation is slow, so databases let you choose how much to pay for. Postgres defaults to read committed (each statement sees the latest committed data). MySQL InnoDB defaults to repeatable read (one snapshot for the whole transaction). Serializable behaves as if transactions ran one at a time, and some transactions fail and must retry. The SQL & Databases course covers each letter of ACID in Transactions and ACID, and each level and its anomalies in Isolation Levels and Anomalies. For a design, the one bug you must know is below.

The classic bug at read committed is the lost update: two requests read a stock count of 1, both subtract 1, both write 0, and you sold one item twice. Fix it with an atomic statement (UPDATE items SET stock = stock - 1 WHERE id = 7 AND stock > 0), a row lock (SELECT ... FOR UPDATE), or a stricter isolation level.

Quick check
Two checkout requests run at the same time. Both run SELECT stock (gets 1), then UPDATE items SET stock = 0. One item is sold twice. Which fix is simplest and correct?
Need a nudge? A hint rules out a wrong answer.

Indexes: fast reads, slower writes

Without an index, SELECT * FROM users WHERE email = 'ada@example.com' reads every row (a sequential scan). An index is a separate sorted structure that maps email to the row's location, so the database jumps straight there.

Most indexes are B-trees: a wide, shallow, sorted tree. Each node is a disk page holding hundreds of keys, so each level multiplies how many rows you can reach by several hundred. Even billions of rows need only a handful of page reads.

Pythonbtree_depth.py
import math def btree_levels(rows, fanout=500): # each page holds ~500 keys, so each level multiplies reach by 500 return max(1, math.ceil(math.log(rows, fanout))) for rows in [10_000, 1_000_000, 100_000_000, 10_000_000_000]: scan = rows # no index: look at every row seek = btree_levels(rows) # index: one page read per level print(f"{rows:>14,} rows full scan {scan:>14,} rows B-tree {seek} page reads")
Output
Press Run (⌘ Enter) to see what happens.

Indexes are not free. Every INSERT, UPDATE, or DELETE must also update every index on the table, and each index takes disk and memory. A table with eight indexes does roughly nine writes per insert. So you index the columns your frequent queries filter, join, or sort on, and nothing else. Use EXPLAIN ANALYZE to see whether a query uses an index. How Indexes Work and Reading EXPLAIN and EXPLAIN ANALYZE in the SQL & Databases course go deeper; here you only need the trade.

CREATE INDEX idx_orders_user_created ON orders (user_id, created_at DESC);
 
EXPLAIN ANALYZE
SELECT * FROM orders WHERE user_id = 42 ORDER BY created_at DESC LIMIT 20;
-- Index Scan using idx_orders_user_created ... (actual time=0.03..0.05 rows=20)
Quick check
An event-logging table receives 30,000 inserts per second and is queried once a day for a report. Someone adds six indexes to speed up the report. What happens?
Need a nudge? A hint rules out a wrong answer.

Normalization vs denormalization

Normalization means storing each fact exactly once and referencing it by id. The user's name lives in users, and posts store user_id. Updates touch one row and data cannot disagree with itself, but reads need joins.

Denormalization means copying data where it is read, to avoid joins. A post row also stores author_name; a counter column stores comment_count instead of counting rows. Reads are faster, but every copy must be kept in sync when the source changes.

NormalizedDenormalized
ReadsNeed joinsOne lookup
WritesUpdate one placeUpdate every copy
RiskSlow joins at huge scaleCopies drift out of sync
Typical homeRelational OLTP databasesNoSQL, read-heavy feeds, analytics

Start normalized. Denormalize specific hot read paths when measurements show joins are the bottleneck.

When Postgres is the right default

For a new product, PostgreSQL is the right default unless you have a concrete reason otherwise. One well-tuned Postgres server handles tens of thousands of simple queries per second and several terabytes of data. It does relational data, JSON documents (JSONB), full-text search, geospatial queries (PostGIS), vector search (pgvector), and queues (SKIP LOCKED). With read replicas and table partitioning it goes a long way before you need sharding.

Reach for something else when the numbers say so: write volume beyond what one primary can take (think hundreds of thousands of writes per second), a pure key-value workload at massive scale (DynamoDB), or search quality Postgres cannot match (OpenSearch).

Quick check
A startup is building a marketplace: users, listings, orders, reviews. They expect 50,000 users in year one. Which database should they start with?
Need a nudge? A hint rules out a wrong answer.
Key terms
ACID
Atomicity, consistency, isolation, durability: the guarantees of a relational transaction.
isolation level
How much concurrent transactions can see of each other. Postgres defaults to read committed.
B-tree index
A shallow sorted tree that finds a row in a few page reads, at the cost of extra work on every write.
normalization
Storing each fact once and joining by id. Denormalization copies data to avoid joins.
wide-column store
Cassandra-style database: rows grouped by partition key, built for huge write volume and known queries.
access pattern
The queries a system runs and how often. The main input when choosing a database and its keys.