Summary#
A relational database (RDBMS) stores data in tables of rows and columns, links tables with keys, and lets you ask questions in SQL, a declarative language: you say what you want and the query optimizer decides how to get it. It enforces correctness with constraints and groups changes into transactions that succeed or fail as a whole. PostgreSQL and MySQL are the most common open-source choices. A single well-tuned node handles thousands of writes per second and terabytes of data, which is enough for most products; beyond that you add replicas and, eventually, sharding.
Why It Exists#
Most business data is related: users place orders, orders contain products, products belong to categories. Storing that in files or ad-hoc structures leads to duplicated data, broken references and code that must re-implement searching and consistency. Relational databases, based on E. F. Codd's relational model from 1970, solve this once: a clear structure, a general query language and strong guarantees. They remain the default for most applications. This page builds on Storage Fundamentals.
How It Works#
Tables, rows, primary and foreign keys#
- A table holds one kind of entity, such as
usersororders. Each row is one entity; each column has a name and a type. - A primary key uniquely identifies each row (for example,
id). It must be unique and not null. - A foreign key is a column that refers to a primary key in another table (
orders.user_idrefers tousers.id). The database rejects references to rows that do not exist.
The relational model in depth#
Where it came from. In 1970, Edgar F. Codd, a researcher at IBM, published "A Relational Model of Data for Large Shared Data Banks". Before it, databases were mostly navigational. Programs followed pointers from one record to the next, so every query was a hand-written walk through the data, and changing the storage layout broke the programs. Codd's idea was to describe data as relations (tables) of tuples (rows), and to let programs say what data they want, using operations from set theory and logic, while the system works out how to fetch it. IBM's System R project in the 1970s built a prototype and the language that became SQL. Oracle, then IBM's own products, brought it to market. Fifty years later, the same separation between the logical model and the physical storage is why a decade-old query can still run unchanged on a new storage engine.
Schema on write. A relational table has a fixed schema: named columns, each with a type and optional constraints. Every row must fit it at the moment it is written. That is the opposite of a schemaless document store, where structure is checked only when the data is read, if at all. Schema on write costs flexibility, because a new field needs a migration, but it buys a lot. Every reader can trust the shape of the data, the database can store it compactly, and bad data is rejected at the door instead of being discovered months later in a report.
Declarative queries. SQL describes the result, not the steps. SELECT name FROM users WHERE email = 'a@b.com' does not say whether to scan the table or use an index. The query optimizer decides, and it can decide differently tomorrow if the data grows or a new index appears. This is the main reason relational databases are so adaptable. When a product team asks a new question, you usually write a new query, perhaps add an index, and the existing data model still works.
Why relational is the default for product designs. Most product data is transactional: user accounts, orders, payments, bookings, inventory. It has clear entities and relationships, it must be correct, and the questions asked of it change over time. Relational databases fit all three needs, which is why they are the sensible starting point in most product-style design interviews and in most real products. Choose something else when a specific requirement pushes you there, such as an enormous write rate, a schemaless shape or graph traversals, not by default.
Keys in depth#
Surrogate versus natural primary keys. A natural key is real-world data that happens to be unique, such as an email address, a username or a national ID number. A surrogate key is a system-generated identifier, such as user_id = 81234, with no meaning outside the database. Prefer surrogate keys for almost everything. Natural keys change (people change emails), sometimes turn out not to be unique after all, and spread personal data into every table that references them. A surrogate key stays stable forever, however the business rules change. Keep the natural value as an ordinary column with a UNIQUE constraint, so you still get its uniqueness guarantee.
Choosing the ID type.
| Option | How it works | Strengths | Weaknesses |
|---|---|---|---|
Auto-increment integer (BIGSERIAL, AUTO_INCREMENT) | Database hands out 1, 2, 3 and so on | Compact (8 bytes), ordered, fast inserts | Needs one central counter; IDs leak volume ("we are order 1,042"); hard to merge across shards |
| Random UUID (version 4) | 128 random bits generated anywhere | No coordination, safe to create on clients | 16 bytes; random insert positions fragment B-tree indexes and hurt cache locality |
| Time-ordered UUID (version 7) or ULID | Timestamp prefix plus random bits | Generated anywhere, roughly ordered, so inserts stay index-friendly | 16 bytes; reveals creation time |
| Snowflake-style 64-bit ID | Timestamp, machine ID and sequence packed in 64 bits | Compact, ordered, generated without a central counter | Needs machine-ID assignment and clocks that do not jump backwards |
A clustered primary key, as in MySQL's InnoDB, stores rows in key order, so random UUIDs there scatter every insert across the table. That is a real, measurable slowdown at high insert rates, and it is why ordered IDs are preferred for large, write-heavy tables.
Composite keys. Some tables are naturally identified by two columns. A likes table can use PRIMARY KEY (user_id, post_id). That one declaration both identifies each like and guarantees that a user cannot like the same post twice. Column order matters. The key above makes "all posts this user liked" fast, but "all users who liked this post" needs a second index on (post_id, user_id).
Foreign keys in depth. A foreign key declares that posts.user_id must match an existing users.id. The database checks it on every insert and update of the post, and on every delete or key change of the user. That referential integrity prevents orphaned rows: a post whose author does not exist, or a comment on a deleted post. You choose what happens when the referenced row is deleted:
ON DELETE RESTRICT(orNO ACTION): refuse to delete a user who still has posts.ON DELETE CASCADE: delete their posts too. This is convenient, but one delete can remove millions of rows and hold locks for a long time.ON DELETE SET NULL: keep the posts but clear the author, which suits optional relationships.
Foreign keys have a cost. Each insert must look up the parent row, and deletes on the parent must check the children. Always index the foreign-key column on the child side, because otherwise deleting one parent scans the entire child table. At very large scale, and especially once tables are sharded across databases, where the database cannot check a reference into another shard anyway, some companies drop foreign keys and enforce integrity in application code and background checks. That is a deliberate trade of safety for write speed and operational flexibility. Mentioning it in an interview shows you understand both sides.
Normalisation in depth#
Normalisation means organising tables so that each fact is stored in exactly one place. If a customer's address is copied onto every order, changing it means updating many rows, and missing one leaves the data contradicting itself. The classic normal forms are steps towards "one fact, one place":
- First normal form (1NF): each column holds a single value, with no lists packed into one field. A
tagscolumn holding"red,blue,green"breaks 1NF. A separateitem_tags(item_id, tag)table fixes it. (PostgreSQL array and JSONB columns bend this rule on purpose, which is fine when you never need to join on or constrain the individual items.) - Second normal form (2NF): in a table with a composite key, every non-key column depends on the whole key. In
order_items(order_id, product_id, quantity, product_name), the product name depends only onproduct_id, so it belongs inproducts. - Third normal form (3NF): non-key columns depend only on the key, not on other non-key columns. If
ordersholdscustomer_idandcustomer_email, the email depends on the customer, not the order. Move it tocustomers.
Higher forms (BCNF, 4NF, 5NF) exist, but 3NF is the practical target for most transactional schemas. A useful rule of thumb is "every column describes the key, the whole key, and nothing but the key."
Why normalise: writes are simple and safe (one update per fact), storage is smaller, and integrity is easy to enforce with foreign keys. Why denormalise later: reads that join many tables cost CPU and I/O on every request. A normalised design is the right starting point. You then add copies deliberately where profiling shows a hot read path, accepting the work of keeping them in sync, as described in the scaling section below. Some copies are not really denormalisation at all, because they record history. The price on an order line should be the price at the time of purchase, not a live link to today's product price.
Entities and relationships first. Before writing any table, list the nouns in the requirements (user, post, comment, order) as entities, decide each entity's primary key, then name how they relate (one-to-many, many-to-many) and which side owns the foreign key. Finally, check the design against the queries the product actually runs. A schema that is perfectly normalised but forces a five-way join on the home page is not finished.
Relationships and joins#
- One-to-many: one user has many orders (foreign key on the "many" side).
- Many-to-many: orders and products, through a join table (
order_items). - One-to-one: a user and their profile settings, sometimes split for size or security.
A join combines rows from tables that match on a key:
SELECT o.id, o.status, p.name, i.quantity
FROM orders o
JOIN order_items i ON i.order_id = o.id
JOIN products p ON p.id = i.product_id
WHERE o.user_id = 42
ORDER BY o.id DESC
LIMIT 20;An inner join returns only matching rows; a left join keeps all rows from the left table even with no match (useful for "users with zero orders").
Relationships and joins in depth#
A worked schema. A small social app shows every relationship type at once:
- One-to-many: a user writes many posts, and a post has many comments. The foreign key sits on the "many" side (
posts.user_id). - Many-to-many: users like many posts, and posts are liked by many users. The
likesjoin table has one row per pair, with a composite primary key. - Self-referencing many-to-many:
followslinks users to users, with two foreign keys into the same table. - One-to-one:
user_settingshas exactly one row per user. This is rare in practice and often a sign that the two tables should just be merged. It is justified when one part is large and rarely read, when it has different access controls (sensitive data split out), or when it is optional for most rows.
What a join really does. A join matches rows from two tables on a condition. The kinds you will use:
- Inner join: only pairs that match. Posts with their authors.
- Left (outer) join: every row from the left table, with nulls where there is no match. All users with their post counts, including users with zero posts.
- Semi-join, written with
EXISTSorIN: rows from the left that have at least one match, without duplicating them. Users who have posted at least once. - Anti-join, written with
NOT EXISTS: rows with no match. Users who have never posted. - Self-join: a table joined to itself. Pairs of users who follow each other.
How the database executes a join. The optimizer picks one of three main algorithms:
- Nested loop: for each row on the outer side, look up matches on the inner side, ideally through an index. Excellent when the outer side is small: 20 posts each looking up one author by primary key is 20 index lookups, a fraction of a millisecond.
- Hash join: build a hash table from the smaller input, then stream the larger one past it. Good for large, unsorted inputs with an equality condition, as long as the hash table fits in memory.
- Merge join: walk two inputs that are already sorted on the join key, side by side. Good when both sides come from indexes in the right order.
The algorithm matters less than the number of rows involved. A join that touches 20 rows is fast with any algorithm, and one that touches 50 million rows is slow with all of them.
The feed query: a classic performance trap. "Show the 20 newest posts from people I follow" is one elegant query:
SELECT p.*
FROM follows f
JOIN posts p ON p.user_id = f.followee_id
WHERE f.follower_id = 42
ORDER BY p.created_at DESC
LIMIT 20;For a user who follows 200 people, with an index on posts (user_id, created_at), this is fast: the database reads the newest few posts per followee and merges them. For a user who follows 5,000 accounts that each post often, the database must gather candidates from thousands of index ranges before it can sort and return 20 rows. Under thousands of feed loads per second, this becomes the most expensive query in the system. In interviews, a complex, reporting-style join on the hot path should raise a flag, and the usual fixes come straight from the scaling toolbox:
- Denormalised or precomputed results: keep a per-user feed table (or a Redis list) that is filled when someone posts, so reading the feed is a single indexed range scan. This is "fan-out on write".
- Caching: cache each user's first feed page for a short time.
- Materialised views: let the database maintain the precomputed join, refreshed periodically or incrementally.
The underlying rule: joins are cheap when they are selective and indexed, and dangerous when they are wide and run on every request. Relational databases support arbitrary joins, which is a great strength for flexibility. Minimise them on the hottest paths, and keep them for the queries where flexibility matters.
Joins and scale. Within one database, a join is a local operation. Once data is split across databases, by function (federation) or by key (sharding), a join across them must happen in the application or in a distributed query layer, which is slower and more complex. That is one of the strongest reasons to choose shard keys that keep related rows together, so the common joins stay local to one shard. See Partitioning and Sharding.
Constraints#
Constraints are rules the database enforces on every write, whatever the application code does:
PRIMARY KEYandUNIQUE(no two users with the same email).FOREIGN KEY(no order for a missing user; optionally cascade deletes).NOT NULLandCHECK(quantity > 0,status IN ('pending','paid','shipped')).
Constraints catch bugs and race conditions that application checks miss, such as two requests registering the same email at the same moment.
Constraints in depth#
Constraints beat application checks under concurrency. Suppose the sign-up code checks "is this email taken?" and then inserts the user. Two requests for the same email can arrive at the same moment, both see "not taken", and both insert. No amount of careful application code fixes this without a lock, while a UNIQUE constraint fixes it completely, because the database checks uniqueness atomically inside the index. One insert succeeds, and the other fails with a unique-violation error that the code turns into "email already registered". This is a general rule: invariants that must hold across concurrent requests belong in the database.
The full set.
NOT NULL: the column must have a value. It is cheap, clarifies intent, and lets the optimizer skip null handling.UNIQUE: no duplicates, enforced through an index. It can span several columns, for exampleUNIQUE (event_id, seat_id).PRIMARY KEY:UNIQUEplusNOT NULL, and the row's identity.FOREIGN KEY: references must exist, as described above.CHECK: any condition on the row, such asprice_cents >= 0,end_at > start_at, orstatus IN ('pending', 'paid', 'shipped', 'cancelled').- Partial unique indexes: uniqueness for a subset of rows. For example, PostgreSQL's
CREATE UNIQUE INDEX ON bookings (seat_id) WHERE status = 'active'lets a seat have many cancelled bookings but only one active one. - Exclusion constraints (PostgreSQL): "no two rows may overlap", typically for time ranges.
EXCLUDE USING gist (room_id WITH =, during WITH &&)makes it impossible to double-book a meeting room for overlapping times, even under heavy concurrency.
Deferred constraints. Normally a constraint is checked at each statement. Some databases, PostgreSQL among them, allow DEFERRABLE INITIALLY DEFERRED constraints, which are checked only at commit. That helps when a transaction must temporarily break a rule, for example swapping two rows' positions in an ordered list with a unique position column.
The cost of constraints. Each one is work on every write: an index lookup for UNIQUE and foreign keys, and an expression evaluation for CHECK. For typical OLTP workloads, the overhead is small next to the value of correct data. For bulk loads of hundreds of millions of rows, teams sometimes load first and add constraints and indexes afterwards, which is faster overall.
How a SQL statement executes#
- Parse: check syntax and build a tree.
- Analyse: check that tables and columns exist and types fit.
- Optimise: estimate the cost of different plans (full scan vs index, which join first, which join algorithm) using table statistics, and pick the cheapest.
- Execute: read pages from the buffer pool in memory, loading from disk when needed, and return rows.
EXPLAIN shows the chosen plan. Most slow queries are fixed by adding the right index; see Database Indexing.
How a SQL statement executes in depth#
A worked plan. EXPLAIN ANALYZE shows what the optimizer chose and what actually happened. A simplified PostgreSQL plan for "the 20 newest orders of user 42, with item counts" might look like this:
Limit (rows=20) (actual time=0.09..0.41 ms)
-> Nested Loop Left Join (rows=20)
-> Index Scan Backward using orders_user_created_idx on orders o
Index Cond: (user_id = 42) (actual rows=20)
-> Index Only Scan using order_items_order_idx on order_items i
Index Cond: (order_id = o.id) (actual rows=3 per loop)
Planning Time: 0.15 ms Execution Time: 0.45 msRead it from the innermost lines outwards. The database walks the (user_id, created_at) index backwards to get the newest orders without sorting. For each order, it finds the items through another index. It stops after 20 rows. The same query without the composite index would scan every order of the user and sort them, or, without any index on user_id, scan the whole table. That is the difference between half a millisecond and seconds.
Estimates drive everything. The optimizer picks plans from estimated row counts, which come from statistics: table sizes, distinct values, and histograms of common values. When estimates are wrong, for example after a bulk load before statistics are refreshed, or because two columns are correlated in ways the statistics do not capture, the optimizer can choose a nested loop over millions of rows. Comparing estimated and actual rows in EXPLAIN ANALYZE is the fastest way to diagnose a bad plan. Running ANALYZE, adding extended statistics, or rewriting the query usually fixes it.
Prepared statements and plan caching. Parsing and planning take time, often more than executing a simple indexed query. Prepared statements parse once and can reuse a plan for many executions with different parameters. They also prevent SQL injection, because parameters are never interpreted as SQL text. The risk is a generic plan that is good for typical values but bad for skewed ones, such as a customer with ten million orders. Databases use heuristics to decide when to re-plan.
The buffer pool. Tables and indexes are stored in fixed-size pages (8 KB in PostgreSQL, 16 KB in InnoDB). The database keeps recently used pages in memory, in a buffer pool, and reads from disk only on a miss. A healthy OLTP database serves well over 99% of page reads from memory. When the working set outgrows the buffer pool, the hit rate drops and latency jumps, because every miss is a storage read. See Storage Fundamentals.
Writes go to the log first. An UPDATE changes the page in memory and appends a record of the change to the write-ahead log (WAL). At commit, only the log must be flushed to durable storage, which is a fast, sequential write. Changed data pages are written back later, in the background, during checkpoints. After a crash, the database replays the log from the last checkpoint to restore every committed change. The same log stream feeds replication: replicas apply it to stay in sync.
Transactions intro#
A transaction groups statements so they all succeed or none do:
BEGIN;
UPDATE accounts SET balance = balance - 100 WHERE id = 1;
UPDATE accounts SET balance = balance + 100 WHERE id = 2;
COMMIT; -- or ROLLBACK if anything failedRelational databases give ACID guarantees: atomic, consistent, isolated and durable. Before confirming a commit, the database writes the change to a write-ahead log on disk, so a crash cannot lose committed data. Details, and how concurrent transactions interact, are in ACID and Isolation Levels.
Transactions in depth#
ACID, precisely.
- Atomicity: all of a transaction's changes happen, or none do. A crash halfway leaves no partial transfer.
- Consistency: each transaction moves the database from one valid state to another, as defined by constraints and application rules. The money is moved, never created or destroyed.
- Isolation: concurrent transactions do not see each other's half-finished work. Ideally, the result is as if they ran one after another. In practice, databases offer weaker isolation levels for speed.
- Durability: once committed, a change survives crashes, because it is in the flushed log.
A transaction protects multi-row invariants. Creating a user and their first post together, moving stock from one warehouse to another, booking a seat and recording the payment intent: in each case, a half-done state is a bug. One transaction makes either all of it visible or none of it.
Atomic check-and-act. Consider the dating-app problem of detecting a match. When user A swipes right on B, the system must record the swipe and check whether B already swiped right on A, without a race where both swipes land at once and neither sees the other. In a relational database, this is one transaction: insert A's swipe, then read B's swipe. To be safe under concurrency, it needs either a lock on a row representing the pair, or serializable isolation, so that two simultaneous swipes cannot both miss each other. Wide-column stores such as Cassandra lack general multi-row transactions. A design there gets atomicity by storing both directions in the same partition, using a pair key built from the two sorted user IDs, so that single-partition operations cover both swipes. Some designs move the check to Redis for atomic operations on one key. The relational version is simpler to reason about. The partition-key version scales writes further. The underlying idea is the same: put everything that must change atomically within one unit of atomicity.
Keep transactions short. A transaction holds locks and, in MVCC databases, keeps old row versions alive until it ends. A transaction left open for minutes, for example because the application waits for a user or an external API inside it, blocks other writers and stops cleanup of dead rows. Do the slow work outside the transaction, then open it, make the changes, and commit within milliseconds.
Savepoints and autocommit. Without an explicit BEGIN, most databases run each statement as its own transaction (autocommit). Inside a transaction, SAVEPOINT marks a point you can roll back to without abandoning everything, which is useful for retrying one step. Isolation levels, anomalies and locking are covered in ACID and Isolation Levels and Concurrency Control and Locking.
PostgreSQL vs MySQL#
| PostgreSQL | MySQL (InnoDB) | |
|---|---|---|
| Strengths | Rich SQL, many data types (JSONB, arrays, ranges), extensions (PostGIS, pgvector), strict standards | Simple, fast for common web workloads, huge operational experience |
| Default isolation | Read Committed | Repeatable Read |
| Storage layout | Rows in a heap; indexes point to rows; old versions cleaned by VACUUM | Rows stored in primary-key order (clustered index) |
| Connections | One process per connection; use a pooler (PgBouncer) | One thread per connection |
| Replication | Streaming (physical) and logical replication | Binlog-based replication, Group Replication |
| Fits | Complex queries, varied data types, geospatial, vector search | High-volume simple queries, existing MySQL tooling |
Both are excellent; the choice is often about team experience and ecosystem. Managed versions (Amazon RDS and Aurora, Google Cloud SQL, Azure Database) remove most operational work. See PostgreSQL.
PostgreSQL versus MySQL in depth#
If you have no strong preference, PostgreSQL is a safe default today: it has the broadest feature set and a strong extension ecosystem. MySQL is equally proven at enormous scale, and a team with deep MySQL experience should usually stay with it. The differences that actually matter in production are mostly about internals.
How each stores rows and versions. Both use MVCC (multi-version concurrency control), so readers see a consistent snapshot without blocking writers. They implement it differently:
- PostgreSQL writes a new version of a row into the table (the heap) on every update and marks the old one as dead once no transaction needs it. A background process, VACUUM, later reclaims dead versions. Every index points directly at a row's physical location, so an update that changes the row's location must also update every index, unless the update qualifies as a "HOT" (heap-only tuple) update with free space on the same page. Heavy update workloads can therefore cause bloat: tables and indexes full of dead space, if vacuum falls behind. PostgreSQL also uses 32-bit transaction IDs and must periodically "freeze" old rows, or it risks transaction ID wraparound. Modern versions handle this automatically, but it is a well-known operational hazard on very busy, poorly vacuumed databases.
- MySQL's InnoDB updates rows in place and keeps the old versions in a separate undo log, which readers follow back to reconstruct older snapshots. Rows are stored in a clustered index ordered by primary key, and secondary indexes store the primary key rather than a physical address. A lookup through a secondary index therefore does two index searches: the secondary index to find the primary key, and then the primary index to find the row. Primary-key range scans are very fast, but long or random primary keys make every secondary index bigger and inserts more scattered.
Concurrency and connections. PostgreSQL forks one operating-system process per connection. Each costs several MB of memory and some scheduling overhead, so thousands of direct connections hurt. A pooler such as PgBouncer in front, multiplexing many client connections onto a few dozen server connections, is standard practice. MySQL uses one thread per connection, which is lighter, though large connection counts still need care.
Default isolation. PostgreSQL defaults to Read Committed, where each statement sees data committed before it began. InnoDB defaults to Repeatable Read, where the whole transaction sees one snapshot, and it also uses gap locks to prevent some phantom rows. Code ported between them can behave differently under concurrency, so be explicit about isolation where it matters.
Features. PostgreSQL offers rich types (JSONB with indexing, arrays, ranges, enums), partial and expression indexes, exclusion constraints, transactional DDL (schema changes can be rolled back), and extensions such as PostGIS for geospatial data, pgvector for embeddings, and TimescaleDB for time series. MySQL has narrower features but very mature replication tooling and a long record in high-traffic web stacks. It removed its old query cache in version 8.0, because the cache's global lock hurt concurrency on busy servers.
Schema changes on big tables. Adding a nullable column is instant in modern versions of both. Rewriting a large table, for example by changing a column's type, can lock it for a long time. MySQL users often run online schema-change tools such as gh-ost or pt-online-schema-change, which build a shadow copy and swap it in. PostgreSQL users rely on features like CREATE INDEX CONCURRENTLY and careful migration steps: add a column, backfill it in batches, then add the constraint.
Scale-out ecosystems. Each has a path to horizontal scale. MySQL has Vitess, originally built at YouTube to shard MySQL, which routes queries to shards and manages resharding. PostgreSQL has Citus, an extension that distributes tables across nodes. Cloud-native engines such as Amazon Aurora keep MySQL or PostgreSQL compatibility while replacing the storage layer with a distributed, replicated log-structured store. Distributed SQL databases such as Google Spanner, CockroachDB and YugabyteDB offer SQL and transactions across many nodes and regions, at the cost of higher write latency per transaction because of consensus. SQLite sits at the other extreme: an embedded, single-file database that runs inside the application process, ideal for mobile apps, edge devices, tests and small single-writer services.
Limits of a single node#
One server has finite CPU, RAM, disk and network. Rough limits for a well-tuned primary: about 5,000-20,000 write transactions per second, many more reads (especially from cache), and comfortable operation up to a few terabytes. Beyond that, problems appear: write throughput caps, backups and schema changes take hours, and one machine is a single point of failure. The usual path is vertical scaling first, then read replicas, then partitioning and sharding. See Replication and Partitioning and Sharding.
Scaling a relational database in depth#
"SQL doesn't scale" is mostly a myth. Some of the largest services in the world run on relational foundations: Facebook built its core storage on sharded MySQL for many years, and companies such as Airbnb and Shopify run large relational fleets. Scaling depends less on the database you choose than on how you architect around it. The techniques form a ladder. Climb only as far as your numbers require, because each rung adds complexity.
Tuning first. Benchmark to reproduce the load (tools such as pgbench, sysbench, k6 or JMeter), and profile to find the cause: the slow query log, pg_stat_statements, EXPLAIN ANALYZE. Typical wins:
- Tighten the schema. Use the smallest correct types:
INT(4 bytes, up to about 2.1 billion signed) where it is enough, andBIGINTwhere IDs may exceed it. Use exactDECIMALor integer minor units for money, never floating point. UseNOT NULLwherever a value is required. Keep large blobs out of rows and store a pointer to object storage instead. In MySQL, fixed-lengthCHARcan help for truly fixed-size codes, whileVARCHARsuits variable text. LargeTEXTvalues are stored out of line in both databases, so wide text columns rarely slow down queries that do not select them. - Index for the queries you run: columns used in
WHERE,JOIN,ORDER BYandGROUP BY, often as composite indexes. Each index speeds reads and slows writes, because it must be updated on every insert and update. For very large bulk loads, dropping indexes, loading and rebuilding can be faster. - Avoid expensive joins on hot paths with targeted denormalisation, as below.
- Split hot data from cold. Partition big tables by time, or move rarely used columns to a side table, so the hot part stays in memory.
Read replicas (primary-replica replication). The primary handles all writes and streams its log to one or more replicas, which serve reads. Replicas can feed further replicas in a tree. If the primary fails, the system can keep serving reads, read-only, until a replica is promoted. The costs:
- Replicas lag behind the primary, usually by milliseconds but sometimes by seconds under load, so a user may not see their own write. That is solved with "read your writes" routing to the primary.
- Every replica must replay every write, so a write-heavy primary can bog replicas down. Some systems apply changes on replicas with less parallelism than the primary used to make them, so replicas fall behind even when they have spare hardware.
- More replicas mean more replication traffic and more places for lag.
- If the primary dies before recent writes reach a replica, asynchronous replication can lose them on failover.
- Promotion needs reliable automation to avoid two primaries (split brain).
See Replication.
Multi-primary (master-master). Two or more nodes accept writes and replicate to each other, so writes continue if one fails. The price is steep. The application or a load balancer must decide where to write. Either the nodes coordinate on every write, which adds latency, or they accept writes independently and resolve conflicts afterwards, which weakens ACID guarantees. Conflicts become more frequent with more writers and higher latency between them. Most teams use a single primary per piece of data and reserve multi-primary for specific multi-region needs. See Multi-region Data.
Federation (functional partitioning). Split one large database into several by function: users, products and forums each get their own database. Each one gets less traffic, a smaller working set that fits in memory with better cache hit rates, and its own primary, so writes proceed in parallel. The costs: the application must know which database holds what, joins across functions need application code or a cross-database link, and it does not help if one function's table is itself too big. Microservices often arrive at federation naturally, since each service owns its own database.
Sharding. Split the rows of one table across many databases by a key, such as user ID, so each shard holds a subset. As with federation, each shard has less traffic, smaller indexes, more cache hits and parallel writes, and one shard's failure affects only its users. The costs are serious:
- The application or a routing layer must send each query to the right shard.
- Queries that span shards, and joins across them, become complex or slow.
- Data can be lopsided: a shard holding several very active users runs hot.
- Rebalancing as shards grow is real work, made easier by consistent hashing or by many small virtual shards.
Shard on a key that keeps related data and common queries together, often the user or tenant ID. Naive keys such as the first letter of a last name distribute badly. Details in Partitioning and Sharding and Consistent Hashing.
Denormalisation and materialised views. Most systems read far more than they write, often 100 or even 1,000 reads for every write. When a hot read needs an expensive join, store a redundant, pre-joined copy, such as the author's name on each post row or a per-user order summary, and pay the cost of keeping it in sync on writes. PostgreSQL and Oracle support materialised views, which store the result of a query and refresh it on demand. In PostgreSQL, the refresh recomputes the whole view, so it suits data that can be a little stale. Denormalisation duplicates data, needs care so the copies agree, and can make a write-heavy system slower than its normalised version. Use it where profiling shows the join is the bottleneck. Once data is sharded or federated, denormalising is often the only practical way to avoid cross-database joins.
Placing rows on shards evenly. Once you shard, you need a rule that maps each key to a shard. The obvious rule, shard = hash(user_id) % N, spreads keys evenly, but it breaks badly when N changes. Going from 4 shards to 5 changes the result for about 80% of keys, so almost all data would have to move. Two common fixes:
- Consistent hashing places both shards and keys on a ring of hash values. Each key belongs to the next shard clockwise. Adding a shard takes over only the keys between it and its neighbour, about 1/N of the data. Giving each physical shard many virtual nodes (points on the ring) smooths out uneven ranges, and lets bigger machines take more virtual nodes.
- Many logical shards mapped to fewer physical servers. Hash keys into a fixed, large number of logical shards (say 4,096) and keep a small lookup table from logical shard to database server. To scale out, move whole logical shards to new servers and update the table. No key ever changes its logical shard. Vitess and many in-house MySQL sharding layers use this idea.
Even with perfect hashing, load can be uneven: one celebrity account may get thousands of times more traffic than an average one. Hashing spreads keys, not hotness. Hot keys need separate treatment: caching, splitting the key, or a dedicated shard. See Pattern: Scaling Writes.
When to Use It#
- Data with clear structure and relationships (users, orders, payments, inventory).
- When correctness matters: money, bookings, anything needing transactions and constraints.
- When query patterns are varied or not yet known; SQL can answer new questions without remodelling.
- As the default for a new product until a clear need says otherwise.
Deciding with numbers: will one relational node be enough?#
A quick estimate usually settles the question. Take a marketplace with 10 million monthly users and 1 million daily active users.
- Writes: each active user creates about 5 writes a day (orders, messages, profile edits), so 5 million writes a day. Divided by 86,400 seconds, that is about 60 writes per second on average. With a peak of 10x the average, it is about 600 per second. One primary with NVMe storage handles this with large headroom.
- Reads: with a read ratio of about 50:1, that is 30,000 reads per second at peak. Indexed point reads on a node with a warm buffer pool cost well under a millisecond each, so one large node could carry this. In practice you add two or three read replicas and a cache for safety and failover.
- Storage: with 5 million rows a day at about 1 KB each including indexes, that is about 5 GB a day, or under 2 TB a year. That fits on a single node for years, with old data partitioned by month so it can be archived.
The answer is a single primary with replicas, and sharding stays out of scope. Repeat the exercise at 100x scale (60,000 peak writes per second and 200 TB a year) and sharding or a distributed SQL database becomes the honest answer. The point is to show the threshold with arithmetic rather than by instinct.
Signals that relational is the right primary store:
- The data has many entities with relationships that queries cross: users, their orders, the order items, the products.
- Invariants span rows or tables: a balance that never goes negative, a seat that is never sold twice, totals that must match their line items.
- New questions arrive often: support, finance and analytics teams will ask for reports nobody predicted.
- The write rate fits on one node, or can be partitioned by a key such as tenant or user, so most transactions stay on one shard.
Signals to look elsewhere for part of the system: the data is a giant append-only stream (logs, metrics, clicks), access is purely by key at enormous rates, documents vary wildly in shape, or the queries are search or graph traversal. Even then the relational database usually remains the system of record for the core business entities, with the specialised store alongside it.
When NOT to Use It#
- Very high write volume with simple key access (millions of writes per second): consider a wide-column or key-value store.
- Unstructured blobs such as images and video: use object storage.
- Full-text search or relevance ranking at scale: add a search engine.
- Highly connected graph traversals many hops deep: consider a graph database.
How to Implement It#
- Model entities as tables with primary keys, foreign keys and constraints.
- Write the main queries first and add indexes that support them.
- Use a managed service unless you have a reason to run it yourself.
- Add connection pooling, backups with tested restores, and monitoring of slow queries.
- Scale in order: indexes and tuning, bigger machine, caching, read replicas, then sharding.
| Technology | Fits when |
|---|---|
| PostgreSQL | General default, complex queries, extensions |
| MySQL / MariaDB | Web workloads, existing MySQL expertise |
| Amazon Aurora | Managed Postgres/MySQL compatibility with distributed storage |
| SQLite | Embedded, single-user or edge apps |
Running it in production#
High availability. Run a primary plus at least one synchronous or semi-synchronous replica in another availability zone, with automated failover: managed services such as RDS Multi-AZ or Cloud SQL, or tools such as Patroni for PostgreSQL and Orchestrator for MySQL. Expect failover to take from several seconds to about a minute. Applications must retry on connection errors and must not cache the primary's IP address for long.
Backups and point-in-time recovery (PITR). Replicas are not backups: a bad DELETE replicates instantly. Take periodic full snapshots, archive the WAL or binlog continuously to object storage, and you can restore to any second, for example to just before the mistaken migration. A backup that has never been restored is a hope, not a backup, so schedule regular test restores and measure how long they take. That time is your real recovery time objective (RTO).
Monitoring. Track:
- query latency percentiles and the top queries by total time;
- replication lag;
- connection count against the limit;
- buffer cache hit ratio (a healthy OLTP database usually sits above 99%);
- lock waits and deadlocks;
- disk usage growth;
- in PostgreSQL, dead tuples and transaction ID age.
Alert on trends before limits: a disk 80% full with steady growth is an incident you can still avoid.
Safe change management. Version every schema change as a migration file reviewed like code. Apply additive changes first (new nullable columns, new tables) and destructive ones last, after no code reads the old shape. Set a statement timeout and a lock timeout on migrations, so a migration waiting for a lock does not queue every other query behind it. See Online Data Migrations.
Trade-offs#
| Gain | Cost |
|---|---|
| Strong consistency, transactions, constraints | Writes limited by one primary node without sharding |
| Flexible queries and joins | Joins get expensive across shards |
| Mature tooling and skills | Schema changes need care on large tables |
| Strong consistency with ACID transactions | Write scaling beyond one primary needs sharding work |
| Flexible ad hoc queries and joins | Joins become hard once data is sharded |
| Constraints enforce correctness centrally | Constraints and indexes add write cost |
Common Pitfalls#
- Missing indexes on foreign keys and filter columns.
- Enforcing uniqueness only in application code.
- Opening one connection per request without a pool.
- Using floating point for money instead of
DECIMALor integer cents. - Reading from a lagging replica right after a write and showing stale data to the user who made it.
- Running a long table rewrite in one migration and locking a hot table for minutes.
- Leaving long-running idle transactions open, which blocks vacuum in PostgreSQL and lets undo history grow in InnoDB.
Real-World Examples#
Many large companies run relational databases at scale; Facebook, for example, has long stored core data in large fleets of sharded MySQL.
Other well-documented examples: YouTube built Vitess to shard MySQL as it outgrew a single database, and Vitess is now a CNCF project used by companies such as Slack. GitHub runs large MySQL clusters and built gh-ost to change schemas on huge tables without locking them. Instagram scaled on sharded PostgreSQL in its early growth, using IDs that embed a timestamp and a shard number so rows can be routed and sorted without a central counter.
In the Interview#
How to talk about relational databases in an interview#
Interviewers rarely want a lecture on SQL. They want to see that you pick the database for a reason and size it with numbers. A good flow takes four steps.
- Name the data and the access patterns. "Users, orders and payments, with relationships between them. The main reads are 'orders for a user, newest first' and 'order by ID'. Writes are about 2,000 per second at peak."
- Justify relational. "We need multi-row transactions (an order and its payment change together), uniqueness (one account per email), and flexible queries for support and analytics. A relational database gives us all three."
- Size one node. A well-tuned PostgreSQL or MySQL primary on modern hardware handles thousands to tens of thousands of simple writes per second and far more indexed reads. Storage of a few TB per node is routine. If your estimate fits within those numbers with headroom, say so, and add read replicas for read scaling and failover.
- Describe the next rung. "If writes grow 10x, I would first cache and tune, then shard by user ID, because almost every query is scoped to one user, so it stays on one shard."
Common follow-ups and strong answers:
- "How do you avoid a hot shard?" Choose a high-cardinality key (user ID, not country), hash it, and use many virtual shards so the busiest ones can move to their own hardware.
- "How do you run a migration on a billion-row table?" Add the column as nullable, backfill it in small batches with throttling, deploy code that writes both old and new forms, then add the constraint and switch reads. Use online tools such as gh-ost for rewrites in MySQL.
- "What happens when the primary fails?" An orchestrator detects the failure in seconds, promotes the most up-to-date replica and repoints clients. With asynchronous replication a few recent writes can be lost. Synchronous replication to at least one replica avoids that loss, at the cost of slower writes.
- "How do you handle a count or ranking that is too slow?" Precompute it: keep a counter column updated in the same transaction, or use a materialised view or cache refreshed periodically.
Common interview mistakes with relational databases#
- Reaching for sharding on day one. Sharding adds routing, cross-shard queries and rebalancing work. Show you know a single primary often handles the first years of a product.
- Ignoring the index. Saying "query the orders table" without stating the index (
(user_id, created_at DESC)) leaves the interviewer wondering whether you know the query would scan the table. - Treating replicas as consistent. Reading your own write from a lagging replica is a classic bug. Mention read-your-writes routing.
- Forgetting connection limits. Thousands of stateless app instances each opening tens of connections can exhaust the database. Mention a pooler.
Deep Dive: What the optimizer is really doingShow
The optimizer uses statistics (row counts, value distributions) to estimate how many rows each step returns, then compares plans. For joins it chooses among nested loop (good when one side is small and the other indexed), hash join (build a hash table of the smaller side) and merge join (both sides sorted). Stale statistics cause bad estimates and slow plans, which is why databases run ANALYZE regularly. When a query suddenly slows down without code changes, a plan change is a common cause.
Deep Dive: Write-ahead logging and crash recoveryShow
How can a database promise that a committed transaction survives a power cut, while still keeping most data in memory? The answer is the write-ahead log (WAL), called the redo log in InnoDB.
The rule is simple: before a changed data page reaches disk, the log record that describes the change must already be on disk. At commit, the database flushes the log up to the commit record with fsync, and only then reports success. The changed data pages themselves stay in the buffer pool and are written later, lazily, by background writers and at checkpoints. Commit cost is therefore one sequential log write, not many random page writes. On an NVMe drive an fsync often takes tens to a few hundred microseconds. On a network-attached cloud volume it can take about a millisecond or more, and that sets a floor on single-connection commit latency.
Group commit amortises the fsync: when many transactions commit at about the same moment, one flush covers all their records. That is why throughput keeps rising with concurrency even though each commit must wait for the disk.
Recovery after a crash follows the ideas formalised in the ARIES algorithm (C. Mohan and colleagues at IBM, 1992):
- Analysis: read the log from the last checkpoint to find which transactions were active and which pages might be dirty.
- Redo: replay the log forward and reapply every change, even those of uncommitted transactions, bringing pages to their exact state at the moment of the crash.
- Undo: roll back the transactions that never committed, logging the undo steps too, so that a crash during recovery is also safe.
Checkpoints bound recovery time. They write dirty pages out and record a point in the log before which no replay is needed. Frequent checkpoints mean fast recovery but more write I/O. Infrequent ones mean the reverse. This is a tunable trade-off (checkpoint_timeout and max_wal_size in PostgreSQL).
The same log does a second job: replication. A replica that receives and replays the primary's WAL stream ends up byte-for-byte identical (physical replication). A logical decoding of the log ("row X changed from A to B") powers logical replication and change data capture tools such as Debezium. See Change Data Capture.
A subtle production lesson: durability depends on every layer honouring fsync. Disks or virtual volumes with volatile write caches that report a write as done before it really is can silently break the guarantee. In 2018 PostgreSQL developers found that on Linux a failed fsync could clear the error state, so a retry would falsely succeed. The resulting fix makes PostgreSQL treat an fsync failure as fatal and recover from the WAL.
Key Takeaways#
- Relational databases store tables linked by primary and foreign keys, queried with SQL.
- The optimizer turns declarative SQL into an execution plan;
EXPLAINshows it. - Constraints and transactions keep data correct even when application code has bugs.
- PostgreSQL and MySQL are both strong defaults; choose by features and team experience.
- One node goes far; scale with tuning, bigger hardware, replicas, then sharding.
- Keys, constraints and transactions push correctness into the database, where every application path gets it for free.
- The WAL makes commits durable with one sequential write and doubles as the replication stream.
- PostgreSQL keeps versions in the heap and needs vacuum. InnoDB clusters rows by primary key and keeps old versions in undo logs.
- Climb the scaling ladder in order: tune, scale up, cache, pool, replicate, partition, federate, then shard.