← Building blocks

Default to a relational database

Storage & data modellingfundamental

Structured data with relationships, transactions and ad-hoc queries.

Say it like this

The data is structured, needs transactions and will be queried in ways we have not planned yet, so I start on Postgres with replicas and only shard when the numbers say one primary cannot take the writes.

Basic solution

Use Postgres or MySQL. It covers most products to a few TB with replicas and indexes.

PostgresMySQLAuroraCockroachDB

One primary, WAL, and replicas

Writes go to the primary, hit the WAL first and the B-tree pages second. Replicas replay the WAL and take reads, so the primary is only the write path plus read-after-write.

How it works

  1. Tables hold rows with a fixed schema; a primary key identifies each row and foreign keys relate tables, so the database can refuse an order row that points at a customer that does not exist.
  2. A write goes to the primary. The database first appends the change to the write-ahead log and fsyncs it, so the change survives a crash; then it updates the affected B-tree pages in memory and acknowledges the client. The modified pages are written to the data files later, at checkpoints, in batches.
  3. A transaction groups several statements. MVCC (multi-version concurrency control) keeps the old version of a row alongside the new one, so each transaction reads a consistent snapshot as of its start without blocking writers. Commit makes all of the transaction's changes visible at once, or rollback discards all of them.
  4. A read goes through the planner, which estimates the cost of each way to run the query. It uses an index when the WHERE clause matches a small fraction of rows, otherwise it scans the table; a join between two tables runs as a nested loop (probe the inner table once per outer row), a hash join (build a hash table of one side) or a merge join (walk two sorted inputs), depending on the sizes involved.
  5. Replicas receive the write-ahead log as a stream and apply the same changes to their own copies. Reads can go to them, a few milliseconds behind. Writes stay on the one primary.
  6. When one primary cannot take all the writes, you shard by a key: each shard is a separate database holding the rows whose key falls in its range, the application routes each query to the right shard, and queries that join across shards are no longer possible in one statement.

What you get for free

  • Transactions, constraints, secondary indexes on anything, joins and ad-hoc reporting.
  • Decades of tooling: backups, point-in-time recovery, migrations, monitoring.

Worked example

URL shortener on Postgres

  • 100M new links/month ≈ 40 writes/s, 4,000 reads/s average, 40K at peak.
  • Row: alias (7 chars) + long_url (avg 200 B) + owner + timestamps ≈ 500 B. 6B rows over 5 years ≈ 3 TB with indexes, which fits on one large node's disks.
  • Writes: 40/s is nothing; a single primary handles ~5–10K simple inserts/s on ordinary hardware, so there is more than 100× headroom.
  • Reads: the primary key index on alias is 7 bytes wide; a point read is one index descent, ~1 ms. Put a cache in front and the database sees ~2K reads/s at peak, which two read replicas absorb with headroom.
  • Storage: 3 TB on one node is fine on NVMe, but the working set (hot aliases) is a few GB, so the buffer cache keeps the hot path in memory and most reads never touch the disk.
  • When to shard: not for this scale. Mention that at 10× you would range-shard by alias prefix (62 buckets) and that "list my links" then needs a user_id index per shard or a separate table, because a user's links would be spread across all 62 shards.

Variants and when each wins

Postgres / MySQL (single primary, replicas)

  • One node takes all writes and streams them to replicas that serve reads, with the full SQL feature set. It wins as the default because vertical scaling plus replicas takes you to a few TB and tens of thousands of writes per second with no application changes.

Managed clustered SQL (Aurora, Cloud SQL)

  • The same engine with storage decoupled from compute and replicated six ways across zones. It wins when you want failover in tens of seconds and replica lag in milliseconds without running it yourself, and you are willing to pay for the convenience.

Distributed SQL (CockroachDB, Spanner, YugabyteDB)

  • The data is sharded automatically across nodes and regions while SQL and transactions are kept. It wins when you need writes in several regions or automatic resharding; the costs are higher write latency because each commit needs consensus, and fewer extensions.

Application-level sharding (Vitess, Citus, hand-rolled)

  • Keep Postgres or MySQL, split the tables by tenant or user id, and route each query in a proxy. It wins on cost per node and on keeping a familiar engine, and loses when cross-shard queries and rebalancing become your problem.

Start with one Postgres primary and replicas; move to distributed SQL only when multi-region writes or automatic resharding is a real requirement.

Failure modes

Primary saturated on writes

  • You notice commit latency climbing, replication lag growing and connections piling up waiting for the database. It happens because every write in the system lands on the one primary, and it has run out of disk or CPU headroom. Batch writes, drop indexes nobody queries, move counters and logs to a store built for them, and only then shard by a key the hot path always carries.

Replica lag surprises users

  • You notice a user saving a change and the next page showing the old value. It happens because the follow-up read was served by a replica that had not yet applied the write. Route reads that follow a write to the primary for a short window, or pin the session to a replica only once it has applied the write's LSN.

Lock contention and deadlocks

  • You notice transactions waiting on each other and some aborting with deadlock errors. It happens because long transactions hold row locks while they wait, or two transactions update the same rows in different orders and each waits for the other. Keep transactions short, update rows in a fixed key order, and use optimistic version checks for the hottest rows.

Table bloat and vacuum debt

  • You notice disk usage growing although the row count does not, and queries getting slower. It happens because MVCC keeps dead row versions until vacuum reclaims them, and a long-running transaction stops vacuum from removing versions it might still need. Watch for old transactions, tune autovacuum to run more often, and avoid patterns that update one row on every request.

Schema change locks the table

  • You notice a migration blocking every query on a table for minutes. It happens because the migration rewrote the table or built an index without CONCURRENTLY, which takes a lock that every read and write waits behind. Use expand-then-contract migrations, build indexes online, and backfill in small batches.

Interviewer follow-ups

Answer out loud before you open each one.

When would you not start with a relational database?

When the access pattern is a pure key lookup at huge volume (key-value), when rows are append-only and read as ranges per key at tens of TB (wide-column), or when the main query is a deep traversal. Even then I would often keep a relational store for the metadata beside it.

How do you scale reads before you scale writes?

A cache in front for the hot keys, then read replicas for everything else, then indexes and query tuning. Reads are usually 10–100× writes, so this buys an order of magnitude before the primary is the limit.

What is MVCC and why does it matter here?

Multi-version concurrency control keeps old row versions so readers never block writers; each transaction sees a snapshot. The cost is garbage: dead versions need vacuuming, and a long transaction prevents cleanup, so bloat is an operational concern.

How would you shard this if you had to?

Pick the key the hot queries always carry, hash or range it into N buckets, put a router in front, and keep each shard a normal replicated Postgres. Cross-shard reads go through a scatter-gather layer or a separate analytics copy; cross-shard writes are avoided by design.

Connections

Built on
B-tree
Pairs with
Spread reads across replicas · Index the columns you filter on · Pool database connections · Partition the data · Change the schema without downtime
Pulls against
Append-heavy, time-ordered rows · Accept a short delay for scale
Used in
URL Shortener (TinyURL / bit.ly) · Ride Matching (Uber / Lyft)

The same parts on other clouds

The diagrams above name AWS services as one concrete example. Every part has a close equivalent elsewhere. In an interview, name the role first, such as “a managed Redis cache”, then the product you would pick.

AWSUsed here asGoogle CloudMicrosoft AzureOpen source and others
Amazon EC2 Auto ScalingServiceCompute Engine managed instance groupsVirtual Machine Scale SetsKubernetes Deployment with a HorizontalPodAutoscaler, Nomad
Amazon AuroraPostgres primary, Replica 1, Replica 2AlloyDB for PostgreSQL, Cloud SQLAzure Database for PostgreSQL or MySQLPostgreSQL, MySQL, CockroachDB
Amazon S3WAL archiveCloud StorageBlob StorageCloudflare R2, MinIO, Ceph